Skip to contentSkip to conversation

worktree list: add --merged and --no-merged

RFC PATCH In review Jasper Mayone 7 participants 59 messages Oct 21 – Nov 19 Documentation

lore
Share & tools
lore
#0 lore raw

cover worktree list: add --merged and --no-merged

I keep one worktree per topic. When a topic lands, its branch stays checked out in that worktree, so "git branch --delete-merged" skips it, and there is no direct way to ask which worktrees are done. In the --delete-merged squash thread [1] I said I would send an RFC for this. Here it is.

This patch teaches "git worktree list" the --merged and --no-merged filters that "git branch", "git tag" and "git for-each-ref" already have, applied to the HEAD of each worktree:

    $ git worktree list --merged origin/main
    /src/proj            1a2b3c4 [main]
    /src/proj-topic-a    5d6e7f8 [topic-a]
    /src/proj-fix-b      9a8b7c6 (detached HEAD)

It only lists. Removing stays a separate step with "git worktree remove", which already refuses a dirty or locked worktree and the main worktree, so a script can do:

    git worktree list --porcelain --merged origin/main |
    sed -n "s/^worktree //p" |
    while read -r wt; do git worktree remove "$wt"; done

The test is strict reachability, the same as "git branch --merged". A worktree whose topic was squash or rebase merged upstream is not listed. If Harald's "has this landed" check ends up as a helper, a later option could use it here too, but I kept that out of this RFC.

Questions for the list:

1. The main worktree is filtered like any other, so it is usually listed. "git branch --merged" also lists the current branch, so I kept that. Should it be left out instead?

2. The commit defaults to HEAD, like the ref filters. For cleanup, each worktree's branch upstream would often be the more useful default, but that is a different meaning for the same option name. Is HEAD the right default?

3. I reused struct ref_filter and OPT_MERGED from ref-filter.h, so the parsing, the default and the error messages match the other commands. It only needs the two commit lists. Is that acceptable, or would you prefer a small local option callback? If the reuse is fine, --contains and --points-at could follow the same way.

4. Is a later "git worktree remove --merged <commit>" (with --dry-run) wanted, or should removal stay in scripts?

[1] https://lore.kernel.org/git/[email protected]/

Jasper Mayone (1):
worktree list: add --merged and --no-merged

 Documentation/git-worktree.adoc |  24 +++++-
 builtin/worktree.c              |  80 +++++++++++++++++++-
 t/t2402-worktree-list.sh        | 125 ++++++++++++++++++++++++++++++++
 3 files changed, 226 insertions(+), 3 deletions(-)

base-commit: 47fdf2208c5b94c8cc01c106b8f7c85efb91c926

Signature · 1 line
2.56.0
#1 lore raw

RFC PATCH 1/1 worktree list: add --merged and --no-merged

Users who keep one worktree per topic have no direct way to find the worktrees whose work has already landed. "git branch --merged" lists the branches, but the user then has to match each branch to a worktree by hand, and a detached worktree has no branch to match. "git branch --delete-merged" skips any branch that is checked out in a worktree, so these are exactly the branches it leaves behind.

Teach "git worktree list" the same --merged and --no-merged filters that "git branch", "git tag" and "git for-each-ref" have, applied to the HEAD of each worktree. The options are parsed by the same OPT_MERGED and OPT_NO_MERGED helpers, so the default (the HEAD of the current worktree), the error messages and the rules for combining them are the same: a worktree is shown when its HEAD is reachable from at least one of the --merged commits and from none of the --no-merged commits.

A bare worktree, a worktree on an unborn branch, and a worktree whose HEAD cannot be read have no HEAD commit, so the filters leave them out. Both output formats are kept, so the result can be used directly with "--porcelain -z":

    git worktree list --porcelain -z --merged origin/main

Nothing is removed. Removing the worktrees stays a separate step with "git worktree remove", which already refuses a dirty or locked worktree.

---
 Documentation/git-worktree.adoc |  24 +++++-
 builtin/worktree.c              |  80 +++++++++++++++++++-
 t/t2402-worktree-list.sh        | 125 ++++++++++++++++++++++++++++++++
 3 files changed, 226 insertions(+), 3 deletions(-)
Documentation/git-worktree.adoc +23 -1
index e6e77252ab..817766b07c 100644
@@ -11,7 +11,7 @@ SYNOPSIS
 [synopsis]
 git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]
 		 [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]
-git worktree list [-v | --porcelain [-z]]
+git worktree list [-v | --porcelain [-z]] [--merged [<commit>]] [--no-merged [<commit>]]
 git worktree lock [--reason <string>] <worktree>
 git worktree move <worktree> <new-path>
 git worktree prune [-n] [-v] [--expire <expire>]
@@ -114,6 +114,11 @@ whether the worktree is bare, the revision currently checked out, the
 branch currently checked out (or "detached HEAD" if none), "locked" if
 the worktree is locked, "prunable" if the worktree can be pruned by the
 `prune` command.
++
+With `--merged` or `--no-merged`, only the worktrees whose `HEAD` is
+(or is not) reachable from the given commit are listed. This finds the
+worktrees whose work has landed, for example to remove them with
+`git worktree remove`.
 
 `lock`::
 
@@ -268,6 +273,23 @@ mismatch, even if the links are correct.
 	to parse the output when a worktree path contains a newline
 	character.
 
+`--merged [<commit>]`::
+	With `list`, only list worktrees whose `HEAD` is reachable from
+	_<commit>_. _<commit>_ defaults to the `HEAD` of the current
+	worktree.
+
+`--no-merged [<commit>]`::
+	With `list`, only list worktrees whose `HEAD` is not reachable
+	from _<commit>_. _<commit>_ defaults to the `HEAD` of the current
+	worktree.
++
+When `--merged` and `--no-merged` are combined or repeated, only
+worktrees whose `HEAD` is reachable from at least one of the
+`--merged` commits and from none of the `--no-merged` commits are
+listed. With either option, a bare worktree, a worktree on an unborn
+branch, and a worktree whose `HEAD` cannot be read are not listed,
+because they have no `HEAD` commit.
+
 `-q`::
 `--quiet`::
 	With `add`, suppress feedback messages.
builtin/worktree.c +78 -2

128 lines not on this page · raw message

t/t2402-worktree-list.sh +125 -0

129 lines not on this page · raw message

Signature · 1 line
2.56.0
#2 lore raw
Quoted 6 lines · Jasper Mayone

Users who keep one worktree per topic have no direct way to find the worktrees whose work has already landed. "git branch --merged" lists the branches, but the user then has to match each branch to a worktree by hand, and a detached worktree has no branch to match. "git branch --delete-merged" skips any branch that is checked out in a worktree, so these are exactly the branches it leaves behind.

Real review on this patch never happened, it seems, perhaps because a discussion on a side issue distracted everybody?

It looks like the intro unfairly narrows the problem space. Even for those users who do not use one worktree per topic do need to find worktrees based on what branch they check out. While I agree that among the criteria to choose these branches to filter worktrees on, "--merged" and "--not-merged" may be two of the most useful ones, the feature does not have to be limited to them.

I wonder if "git worktree list --branch=...", where --branch= can be given multiple times, is a better primitive? With that you could do something like

  $ git worktree list $(git branch --contains HEAD | sed -e 's/^/--branch=/')

to reuse the same machinery without any extra code.

#3 lore raw
Quoted 18 lines · Junio C Hamano
Quoted 6 lines · Jasper Mayone

Users who keep one worktree per topic have no direct way to find the worktrees whose work has already landed. "git branch --merged" lists the branches, but the user then has to match each branch to a worktree by hand, and a detached worktree has no branch to match. "git branch --delete-merged" skips any branch that is checked out in a worktree, so these are exactly the branches it leaves behind.

Real review on this patch never happened, it seems, perhaps because a discussion on a side issue distracted everybody?

It looks like the intro unfairly narrows the problem space. Even for those users who do not use one worktree per topic do need to find worktrees based on what branch they check out. While I agree that among the criteria to choose these branches to filter worktrees on, "--merged" and "--not-merged" may be two of the most useful ones, the feature does not have to be limited to them.

Quoted 7 lines

I wonder if "git worktree list --branch=...", where --branch= can be given multiple times, is a better primitive? With that you could do something like

  $ git worktree list $(git branch --contains HEAD | sed -e 's/^/--branch=/')

to reuse the same machinery without any extra code.

I've been too busy lately to allocate time to the Git project, so I didn't read the patch body and only quickly skimmed the commit message, but I experienced the same reaction that this seems overly special-case, and immediately thought of a more general "for-each" sort of mechanism. The analogy which immediately comes to mind is git submodule foreach <command>.

#4 lore raw

PATCH v2 1/1 worktree list: add --branch to select worktrees by branch

There is no direct way to ask which worktree has a given branch checked out. "git worktree list --porcelain" prints the branch of every worktree, so a script has to parse the whole list and match the "branch" lines itself.

Teach "git worktree list" a "--branch=<branch>" option that lists only the worktrees that have <branch> checked out. It can be given more than once. A worktree that is rebasing or bisecting a branch counts as having it checked out, as it does for "git branch -d" and "git worktree add". <branch> is a branch name, or a full name under refs/heads/.

This keeps the choice of branches in "git branch", which already has --merged, --contains, --points-at and patterns. For example, to list the worktrees whose branch is merged into origin/main:

    git worktree list \
	$(git branch --format='--branch=%(refname)' --merged origin/main)

The --format is needed because the default output of "git branch" marks the current branch with "*" and the branches checked out in other worktrees with "+". It uses the full name because %(refname:short) gives "heads/topic" when a tag is also called "topic".

Each worktree's branch is found once and looked up in a set of the requested branches, so feeding it every branch of a large repository stays cheap.

A detached worktree has no branch, so it is never listed.

---
Changes since the RFC [1]:

* Junio pointed out that --merged and --no-merged narrow the problem to one workflow, and suggested selecting worktrees by branch instead, with "git branch" doing the choosing. Eric had the same reaction. This version does that and drops --merged, --no-merged and the reachability code.

* Junio's example piped "git branch" through sed. Its default output prefixes the current branch with "*" and branches checked out in other worktrees with "+", which are the branches this is for, so the words come out as "--branch=+" and "topic". The documented form uses --format='--branch=%(refname)'. The full name also avoids "heads/topic" from %(refname:short) when a tag has the same name.

* <branch> is an exact name, not a pattern, because "git branch" already has --list <pattern>, --merged, --contains and friends. An invalid name dies, as for "git branch -d". A valid name that no worktree has checked out lists nothing.

* Eric, a "git worktree foreach" would be nice, and it could select worktrees with this same --branch. I left it out of this patch.

[1] https://lore.kernel.org/git/[email protected]/

 Documentation/git-worktree.adoc |  21 ++++-
 builtin/worktree.c              |  79 ++++++++++++++++++-
 t/t2402-worktree-list.sh        | 131 ++++++++++++++++++++++++++++++++
 3 files changed, 228 insertions(+), 3 deletions(-)
Documentation/git-worktree.adoc +20 -1
index e6e77252ab..4db11eab88 100644
@@ -11,7 +11,7 @@ SYNOPSIS
 [synopsis]
 git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]
 		 [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]
-git worktree list [-v | --porcelain [-z]]
+git worktree list [-v | --porcelain [-z]] [--branch=<branch>...]
 git worktree lock [--reason <string>] <worktree>
 git worktree move <worktree> <new-path>
 git worktree prune [-n] [-v] [--expire <expire>]
@@ -114,6 +114,9 @@ whether the worktree is bare, the revision currently checked out, the
 branch currently checked out (or "detached HEAD" if none), "locked" if
 the worktree is locked, "prunable" if the worktree can be pruned by the
 `prune` command.
++
+With `--branch`, only the worktrees that have one of the given branches
+checked out are listed.
 
 `lock`::
 
@@ -268,6 +271,22 @@ mismatch, even if the links are correct.
 	to parse the output when a worktree path contains a newline
 	character.
 
+`--branch=<branch>`::
+	With `list`, only list worktrees that have _<branch>_ checked
+	out, including a worktree that is rebasing or bisecting
+	_<branch>_. _<branch>_ is a branch name, such as `topic` or
+	`@{-1}`, or a full name under `refs/heads/`. The option can be
+	given more than once to list the worktrees of several branches.
+	A detached worktree is never listed.
++
+Use linkgit:git-branch[1] to choose the branches. For example, to list
+the worktrees whose branch is merged into `origin/main`:
++
+------------
+$ git worktree list \
+	$(git branch --format='--branch=%(refname)' --merged origin/main)
+------------
+
 `-q`::
 `--quiet`::
 	With `add`, suppress feedback messages.
builtin/worktree.c +77 -2

125 lines not on this page · raw message

t/t2402-worktree-list.sh +131 -0

135 lines not on this page · raw message

base-commit: 7e34d8174dcda3435d1404c9a30bef46afe6c13e

Signature · 1 line
2.56.0
#5 lore raw

Re: [PATCH v2] worktree list: add --branch to select worktrees by branch

Hi Jasper

Quoted 8 lines · Jasper Mayone

There is no direct way to ask which worktree has a given branch checked out. "git worktree list --porcelain" prints the branch of every worktree, so a script has to parse the whole list and match the "branch" lines itself.

Teach "git worktree list" a "--branch=<branch>" option that lists only the worktrees that have <branch> checked out. It can be given more than once.

Playing devil's advocate for a minute that means the script still has to match branch names if it wants to know each branch is checked out. It does make it easier for scripts that are only interested in a single branch though.

Quoted 4 lines

A worktree that is rebasing or bisecting a branch
counts as having it checked out, as it does for "git branch -d" and "git worktree add". <branch> is a branch name, or a full name under refs/heads/.

That's useful because "git worktree list" does not show branch names when they're being rebased or bisected. The commit message should spell that out.

Quoted 2 lines

This keeps the choice of branches in "git branch", which already has --merged, --contains, --points-at and patterns.

This sentence seems to assume the reader has some context from the previous iteration

Quoted 12 lines

For example, to list
the worktrees whose branch is merged into origin/main:

     git worktree list \
	$(git branch --format='--branch=%(refname)' --merged origin/main)

The --format is needed because the default output of "git branch" marks the current branch with "*" and the branches checked out in other worktrees with "+". It uses the full name because %(refname:short) gives "heads/topic" when a tag is also called "topic".

Quoted 3 lines

Each worktree's branch is found once and looked up in a set of the requested branches, so feeding it every branch of a large repository stays cheap.

The implementation seems to duplicate much of branch.c:prepare_checked_out_branches(). It would be nicer to add a preparatory patch (or maybe two patches) that adds a "struct worktree" member to "struct checked_out_branch" and converts "checked_out_branches" to a hashmap indexed by the branch name. Then we can implement "git worktree list --branch" in terms of a new function

const struct worktree *branch_find_checkout(const char *branch);

in branch.c that looks up the branch in "checked_out_branches" and returns the worktree if it is checked out, or it is being rebased or bisected.

Another thing to think about is that normally the main worktree is listed first, but if we are listing a subset of worktrees there is no way to tell from the output if one of them is the main worktree. I think that matters because we don't want to delete the main worktree - "git worktree remove path/to/main-worktree" will die but it would be nice if the script could avoid calling that in the first place. So I think we want another patch that adds something like "is-main-worktree true" when the main worktree is printed.

Is there a reason we reject syntactically invalid branch names, but accept the names of branches that do not exist?

Quoted 1 line

A detached worktree has no branch, so it is never listed.

I'm not sure that sentence is really needed.

Thanks

Phillip

Quoted 357 lines

---
Changes since the RFC [1]:

* Junio pointed out that --merged and --no-merged narrow the problem to one workflow, and suggested selecting worktrees by branch instead, with "git branch" doing the choosing. Eric had the same reaction. This version does that and drops --merged, --no-merged and the reachability code.

* Junio's example piped "git branch" through sed. Its default output prefixes the current branch with "*" and branches checked out in other worktrees with "+", which are the branches this is for, so the words come out as "--branch=+" and "topic". The documented form uses --format='--branch=%(refname)'. The full name also avoids "heads/topic" from %(refname:short) when a tag has the same name.

* <branch> is an exact name, not a pattern, because "git branch" already has --list <pattern>, --merged, --contains and friends. An invalid name dies, as for "git branch -d". A valid name that no worktree has checked out lists nothing.

* Eric, a "git worktree foreach" would be nice, and it could select worktrees with this same --branch. I left it out of this patch.

[1] https://lore.kernel.org/git/[email protected]/

  Documentation/git-worktree.adoc |  21 ++++-
  builtin/worktree.c              |  79 ++++++++++++++++++-
  t/t2402-worktree-list.sh        | 131 ++++++++++++++++++++++++++++++++
  3 files changed, 228 insertions(+), 3 deletions(-)
Documentation/git-worktree.adoc +20 -1
index e6e77252ab..4db11eab88 100644
@@ -11,7 +11,7 @@ SYNOPSIS
  [synopsis]
  git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]
  		 [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]
-git worktree list [-v | --porcelain [-z]]
+git worktree list [-v | --porcelain [-z]] [--branch=<branch>...]
  git worktree lock [--reason <string>] <worktree>
  git worktree move <worktree> <new-path>
  git worktree prune [-n] [-v] [--expire <expire>]
@@ -114,6 +114,9 @@ whether the worktree is bare, the revision currently checked out, the
  branch currently checked out (or "detached HEAD" if none), "locked" if
  the worktree is locked, "prunable" if the worktree can be pruned by the
  `prune` command.
++
+With `--branch`, only the worktrees that have one of the given branches
+checked out are listed.
 
  `lock`::
 
@@ -268,6 +271,22 @@ mismatch, even if the links are correct.
  	to parse the output when a worktree path contains a newline
  	character.
 
+`--branch=<branch>`::
+	With `list`, only list worktrees that have _<branch>_ checked
+	out, including a worktree that is rebasing or bisecting
+	_<branch>_. _<branch>_ is a branch name, such as `topic` or
+	`@{-1}`, or a full name under `refs/heads/`. The option can be
+	given more than once to list the worktrees of several branches.
+	A detached worktree is never listed.
++
+Use linkgit:git-branch[1] to choose the branches. For example, to list
+the worktrees whose branch is merged into `origin/main`:
++
+------------
+$ git worktree list \
+	$(git branch --format='--branch=%(refname)' --merged origin/main)
+------------
+
  `-q`::
  `--quiet`::
  	With `add`, suppress feedback messages.
builtin/worktree.c +77 -2
index 77ecd0f71f..1d7db5f7fc 100644
@@ -15,6 +15,7 @@
  #include "object-name.h"
  #include "parse-options.h"
  #include "path.h"
+#include "strmap.h"
  #include "strvec.h"
  #include "branch.h"
  #include "read-cache-ll.h"
@@ -26,6 +27,7 @@
  #include "submodule.h"
  #include "utf8.h"
  #include "worktree.h"
+#include "wt-status.h"
  #include "quote.h"
 
  #define BUILTIN_WORKTREE_ADD_USAGE \
@@ -33,7 +35,7 @@
  	   "                 [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]")
 
  #define BUILTIN_WORKTREE_LIST_USAGE \
-	N_("git worktree list [-v | --porcelain [-z]]")
+	N_("git worktree list [-v | --porcelain [-z]] [--branch=<branch>...]")
  #define BUILTIN_WORKTREE_LOCK_USAGE \
  	N_("git worktree lock [--reason <string>] <worktree>")
  #define BUILTIN_WORKTREE_MOVE_USAGE \
@@ -1125,11 +1127,78 @@ static void pathsort(struct worktree **wt)
  	QSORT(wt, n, pathcmp);
  }
 
+/*
+ * Return the full name of the branch that "wt" has checked out, or
+ * NULL. A worktree that is rebasing or bisecting a branch has it
+ * checked out, too, as for is_shared_symref().
+ */
+static char *checked_out_branch(const struct worktree *wt)
+{
+	struct wt_status_state state = { 0 };
+	char *ref = NULL;
+
+	if (wt->is_bare)
+		return NULL;
+	if (!wt->is_detached)
+		return xstrdup_or_null(wt->head_ref);
+
+	if (wt_status_check_rebase(wt, &state) &&
+	    (state.rebase_in_progress || state.rebase_interactive_in_progress) &&
+	    state.branch)
+		ref = xstrfmt("refs/heads/%s", state.branch);
+	else if (wt_status_check_bisect(wt, &state) && state.bisecting_from)
+		ref = xstrfmt("refs/heads/%s", state.bisecting_from);
+	wt_status_state_free_buffers(&state);
+	return ref;
+}
+
+/*
+ * Keep only the worktrees that have one of the "--branch" branches
+ * checked out. A branch is given by its name, or by its full name
+ * under refs/heads/.
+ */
+static void filter_by_branch(struct repository *repo, struct worktree **wt,
+			     const struct string_list *branches)
+{
+	struct strset refnames = STRSET_INIT;
+	struct string_list_item *item;
+	struct strbuf ref = STRBUF_INIT;
+	size_t kept = 0;
+
+	for_each_string_list_item(item, branches) {
+		strbuf_reset(&ref);
+		if (starts_with(item->string, "refs/heads/")) {
+			strbuf_addstr(&ref, item->string);
+			if (check_refname_format(ref.buf, 0))
+				die(_("'%s' is not a valid branch name"),
+				    item->string);
+		} else if (check_branch_ref(repo, &ref, item->string)) {
+			die(_("'%s' is not a valid branch name"), item->string);
+		}
+		strset_add(&refnames, ref.buf);
+	}
+
+	for (size_t i = 0; wt[i]; i++) {
+		char *branch = checked_out_branch(wt[i]);
+
+		if (branch && strset_contains(&refnames, branch))
+			wt[kept++] = wt[i];
+		else
+			free_worktree(wt[i]);
+		free(branch);
+	}
+	wt[kept] = NULL;
+
+	strbuf_release(&ref);
+	strset_clear(&refnames);
+}
+
  static int list(int ac, const char **av, const char *prefix,
-		struct repository *repo UNUSED)
+		struct repository *repo)
  {
  	int porcelain = 0;
  	int line_terminator = '\n';
+	struct string_list branches = STRING_LIST_INIT_DUP;
 
  	struct option options[] = {
  		OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
@@ -1138,6 +1207,8 @@ static int list(int ac, const char **av, const char *prefix,
  				N_("add 'prunable' annotation to missing worktrees older than <time>")),
  		OPT_SET_INT('z', NULL, &line_terminator,
  			    N_("terminate records with a NUL character"), '\0'),
+		OPT_STRING_LIST(0, "branch", &branches, N_("branch"),
+				N_("only show worktrees that have <branch> checked out")),
  		OPT_END()
  	};
 
@@ -1157,6 +1228,9 @@ static int list(int ac, const char **av, const char *prefix,
  		/* sort worktrees by path but keep main worktree at top */
  		pathsort(worktrees + 1);
 
+		if (branches.nr)
+			filter_by_branch(repo, worktrees, &branches);
+
  		if (!porcelain)
  			measure_widths(worktrees, &abbrev,
  				       &display, &path_maxwidth);
@@ -1174,6 +1248,7 @@ static int list(int ac, const char **av, const char *prefix,
  		free(display);
  		free_worktrees(worktrees);
  	}
+	string_list_clear(&branches, 0);
  	return 0;
  }
 
t/t2402-worktree-list.sh +131 -0
index eeaf800d74..ea08bf79fa 100755
@@ -318,4 +318,135 @@ test_expect_success 'worktree path when called in .git directory' '
  	test_cmp list1 list2
  '
 
+test_expect_success 'setup for "list --branch"' '
+	git init by-branch &&
+	(
+		cd by-branch &&
+		test_commit base &&
+		git branch topic-a &&
+		git branch topic-b &&
+		git branch unused &&
+		git worktree add ../wt-a topic-a &&
+		git worktree add ../wt-b topic-b &&
+		git worktree add --detach ../wt-detached main &&
+		git -C ../wt-a commit --allow-empty -m a &&
+		git -C ../wt-b commit --allow-empty -m b &&
+		git merge --ff-only topic-a
+	)
+'
+
+list_paths () {
+	git -C by-branch worktree list --porcelain "$@" >out &&
+	sed -n "s/^worktree //p" out >actual
+}
+
+test_expect_success '"list --branch" shows the worktree of that branch' '
+	list_paths --branch=topic-a &&
+	echo "$(pwd)/wt-a" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success '"list --branch" can be repeated' '
+	list_paths --branch=topic-b --branch=main --branch=topic-a &&
+	cat >expect <<-EOF &&
+	$(pwd)/by-branch
+	$(pwd)/wt-a
+	$(pwd)/wt-b
+	EOF
+	test_cmp expect actual
+'
+
+test_expect_success '"list --branch" with a branch that is not checked out' '
+	list_paths --branch=unused --branch=no-such-branch &&
+	test_must_be_empty actual
+'
+
+test_expect_success '"list --branch" never shows a detached worktree' '
+	list_paths --branch=main &&
+	echo "$(pwd)/by-branch" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success '"list --branch" rejects an invalid branch name' '
+	test_must_fail git -C by-branch worktree list --branch=-bad 2>err &&
+	test_grep "is not a valid branch name" err
+'
+
+test_expect_success '"list --branch" keeps the normal output format' '
+	git -C by-branch worktree list --branch=topic-a >out &&
+	sed "s/  */ /g" <out >actual &&
+	echo "$(pwd)/wt-a $(git -C by-branch rev-parse --short topic-a) [topic-a]" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success '"list --branch" works with -z' '
+	git -C by-branch worktree list --porcelain -z --branch=topic-b >out &&
+	tr "\0" "\n" <out >actual &&
+	cat >expect <<-EOF &&
+	worktree $(pwd)/wt-b
+	HEAD $(git -C by-branch rev-parse topic-b)
+	branch refs/heads/topic-b
+
+	EOF
+	test_cmp expect actual
+'
+
+test_expect_success '"list --branch" shows a worktree bisecting that branch' '
+	test_when_finished "git -C wt-b bisect reset && git -C wt-b reset --hard HEAD~2" &&
+	git -C wt-b commit --allow-empty -m b1 &&
+	git -C wt-b commit --allow-empty -m b2 &&
+	git -C wt-b bisect start topic-b topic-b~2 &&
+	test_must_fail git -C wt-b symbolic-ref -q HEAD &&
+	list_paths --branch=topic-b &&
+	echo "$(pwd)/wt-b" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success '"list --branch" shows a worktree rebasing that branch' '
+	test_when_finished "git -C wt-b rebase --abort" &&
+	test_must_fail git -C wt-b rebase -f -x false base &&
+	test_must_fail git -C wt-b symbolic-ref -q HEAD &&
+	list_paths --branch=topic-b &&
+	echo "$(pwd)/wt-b" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success '"list --branch" accepts a full branch name' '
+	list_paths --branch=refs/heads/topic-a &&
+	echo "$(pwd)/wt-a" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success '"list --branch" with a tag of the same name' '
+	test_when_finished "git -C by-branch tag -d topic-a" &&
+	git -C by-branch tag topic-a base &&
+	list_paths --branch=topic-a &&
+	echo "$(pwd)/wt-a" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success '"list --branch" shows unborn and prunable worktrees' '
+	test_when_finished "rm -rf wt-unborn wt-gone && git -C by-branch worktree prune" &&
+	git -C by-branch worktree add --orphan -b unborn ../wt-unborn &&
+	git -C by-branch branch gone &&
+	git -C by-branch worktree add ../wt-gone gone &&
+	rm -rf wt-gone &&
+	git -C by-branch worktree list -v --branch=unborn --branch=gone >out &&
+	test_grep "^$(pwd)/wt-unborn .*\[unborn\]$" out &&
+	test_grep "^$(pwd)/wt-gone .*\[gone\]$" out &&
+	test_grep "prunable: gitdir file points to non-existent location" out
+'
+
+test_expect_success '"list --branch" with "git branch --merged"' '
+	git -C by-branch worktree list --porcelain \
+		$(git -C by-branch branch --format="--branch=%(refname)" \
+			--merged main) >out &&
+	sed -n "s/^worktree //p" out >actual &&
+	cat >expect <<-EOF &&
+	$(pwd)/by-branch
+	$(pwd)/wt-a
+	EOF
+	test_cmp expect actual
+'
+
  test_done

base-commit: 7e34d8174dcda3435d1404c9a30bef46afe6c13e

#6 lore raw

Re: [PATCH v2] worktree list: add --branch to select worktrees by branch

One further thought ...

Quoted 5 lines · Phillip Wood
Quoted 3 lines · Jasper Mayone

For example, to list
the worktrees whose branch is merged into origin/main:

Quoted 8 lines
Quoted 8 lines

     git worktree list \
    $(git branch --format='--branch=%(refname)' --merged origin/main)

The --format is needed because the default output of "git branch" marks the current branch with "*" and the branches checked out in other worktrees with "+". It uses the full name because %(refname:short) gives "heads/topic" when a tag is also called "topic".

I think you can use "%(refname:lstrip=2)" to always remove "refs/heads/" which means we could simplify the implementation and just accept branch names.

Thanks

Phillip

#7 lore raw

Re: [PATCH v2] worktree list: add --branch to select worktrees by branch

In reply to Phillip Wood
Quoted 9 lines · Phillip Wood
Quoted 4 lines · Jasper Mayone

A worktree that is rebasing or bisecting a branch
counts as having it checked out, as it does for "git branch -d" and "git worktree add". <branch> is a branch name, or a full name under refs/heads/.

That's useful because "git worktree list" does not show branch names when they're being rebased or bisected. The commit message should spell that out.

Aside from Philip's excellent review comments, I have a relatively minor question:

Rather than naming it --branch, under the assumption that users may eventually want to filter on other worktree properties, should this new option be given a more generic name, such as --filter=branch:<name>?

If so, that potentially raises the question about how such filter options should combine. It's obvious that multiple --filter=branch:<name> options combine via logical "OR", but a user might want to combine future filter criteria via other logical operations (AND, NOT, grouping). Do other Git commands set precedent regarding filter option naming and logical operations?

Note that I'm not suggesting that this patch should implement such additional filtering behavior (it should not), or even that all these questions need to be answered right now. I'm asking only, taking the above into consideration, whether this option should be given a more generic name to avoid closing the door to those possible future enhancements.

#8 lore raw

Re: [PATCH v2] worktree list: add --branch to select worktrees by branch

Quoted 7 lines · Eric Sunshine

If so, that potentially raises the question about how such filter options should combine. It's obvious that multiple --filter=branch:<name> options combine via logical "OR", but a user might want to combine future filter criteria via other logical operations (AND, NOT, grouping). Do other Git commands set precedent regarding filter option naming and logical operations?

Quoted 6 lines

Note that I'm not suggesting that this patch should implement such additional filtering behavior (it should not), or even that all these questions need to be answered right now. I'm asking only, taking the above into consideration, whether this option should be given a more generic name to avoid closing the door to those possible future enhancements.

Perhaps, but at that point I suspect that the most general form is to allow you to write a callback function that is given the path to the worktree and determines if you want the worktree to be included in the result. Then

	git worktree list --filter-command='
		test 5 -lt $(git rev-list --count master..HEAD)
	'

may become a way to list worktrees with work that has more than 5 commits to be massaged down to 'master', for example.

"git branch --contains" etc. can be expressed inside the framework, so "--branch" may become a special case for that more generalized mechanism.

I dunno.

#9 lore raw

Re: [PATCH v2] worktree list: add --branch to select worktrees by branch

In reply to Jasper Mayone
Quoted 4 lines · Jasper Mayone

There is no direct way to ask which worktree has a given branch checked out. "git worktree list --porcelain" prints the branch of every worktree, so a script has to parse the whole list and match the "branch" lines itself.

git-for-each-ref(1) (and git-branch(1) etc.) have worktreepath.

git worktree add ../test-branch
git worktree remove $(git for-each-ref \
--format='%(worktreepath)' refs/heads/test-branch)
git branch -d test-branch

It will not list the worktree path if that branch is being rebased.

Quoted 31 lines

Teach "git worktree list" a "--branch=<branch>" option that lists only the worktrees that have <branch> checked out. It can be given more than once. A worktree that is rebasing or bisecting a branch counts as having it checked out, as it does for "git branch -d" and "git worktree add". <branch> is a branch name, or a full name under refs/heads/.

This keeps the choice of branches in "git branch", which already has --merged, --contains, --points-at and patterns. For example, to list the worktrees whose branch is merged into origin/main:

    git worktree list \
	$(git branch --format='--branch=%(refname)' --merged origin/main)

The --format is needed because the default output of "git branch" marks the current branch with "*" and the branches checked out in other worktrees with "+". It uses the full name because %(refname:short) gives "heads/topic" when a tag is also called "topic".

Each worktree's branch is found once and looked up in a set of the requested branches, so feeding it every branch of a large repository stays cheap.

A detached worktree has no branch, so it is never listed.

---
[snip]

#10 lore raw

Re: [PATCH v2] worktree list: add --branch to select worktrees by branch

Quoted 8 lines · Kristoffer Haugsbakk

git-for-each-ref(1) (and git-branch(1) etc.) have worktreepath.

git worktree add ../test-branch
git worktree remove $(git for-each-ref \
--format='%(worktreepath)' refs/heads/test-branch)
git branch -d test-branch

It will not list the worktree path if that branch is being rebased.

Thanks, I had missed %(worktreepath). With it, what I wanted from the start is already one command:

    git for-each-ref --merged origin/main \
        --format='%(worktreepath)' refs/heads/

So --branch adds little on top of that. The one real gap is the one you name. While a branch is being rebased or bisected, %(worktreepath) is empty, "git branch" does not mark it with "+", and "git worktree list" shows that worktree as "(detached HEAD)". Yet "git worktree add" and "git branch -d" already treat that branch as checked out.

As Phillip pointed out, branch.c already has this information:
branch_checked_out() covers a plain checkout, a rebase, a bisect and "rebase --update-refs".

So I would like to drop --branch and instead make %(worktreepath) use the same information, so that it names the worktree of a branch that is being rebased or bisected. That is a smaller change with no new option, so the naming question Eric raised and the --filter-command idea Junio floated do not come up.

Is that change in behavior acceptable? A script that reads %(worktreepath) would now get a path for a branch that is being rebased. I think that is a fix, since the rest of Git already considers that branch checked out, but I would like to hear if anyone relies on the empty value.

Phillip, thank you for the review. Your point that "git worktree list" output does not say which entry is the main worktree still stands, and I can send that as a separate patch if it is wanted.

Thanks,
Jasper

#11 lore raw

Re: [PATCH v2] worktree list: add --branch to select worktrees by branch

Quoted 3 lines · Jasper Mayone

Phillip, thank you for the review. Your point that "git worktree list" output does not say which entry is the main worktree still stands, and I can send that as a separate patch if it is wanted.

git worktree list guarantees that the main worktree (or bare repository) is the very first item; this behavior is documented. I think Philip's point was that once filtering is engaged, you lose that
guarantee: in a filtered list, if the main worktree has been filtered away, then the first item will not be the main worktree.

#12 lore raw

Re: [PATCH v2] worktree list: add --branch to select worktrees by branch

In reply to Jasper Mayone

Hi Jasper

Quoted 6 lines · Jasper Mayone

So I would like to drop --branch and instead make %(worktreepath) use the same information, so that it names the worktree of a branch that is being rebased or bisected. That is a smaller change with no new option, so the naming question Eric raised and the --filter-command idea Junio floated do not come up.

That would certainly be a useful improvement, there are a few differences compared to adding something to "git worktree list" though

- "git for-each-ref" does not have an option for NUL terminated output and %(worktreepath) may contain a newline. If is possible to work round that using one of the quoting options, though it is a pain to use those if you're not using one of the supported languages.

- there is no way to know from the output whether deleting a worktree will delete the whole repository.

- I'm not sure that it handles branches that are checked out in more than one worktree. For warning that a branch is in use somewhere that does not matter, but if you want to track down all the places it is checked out it does.

Quoted 5 lines

Is that change in behavior acceptable? A script that reads %(worktreepath) would now get a path for a branch that is being rebased. I think that is a fix, since the rest of Git already considers that branch checked out, but I would like to hear if anyone relies on the empty value.

I think we can consider the change in behavior to be a bug fix.

Quoted 3 lines

Phillip, thank you for the review. Your point that "git worktree list" output does not say which entry is the main worktree still stands, and I can send that as a separate patch if it is wanted.

As Eric said, we only need to mark the main worktree if we're filtering the list of worktrees, otherwise it is always the first one listed.

Thanks

Phillip

#13 lore raw

Re: [PATCH v2] worktree list: add --branch to select worktrees by branch

Quoted 7 lines · Phillip Wood

Hi Jasper

Quoted 1 line · Jasper Mayone
Quoted 7 lines
Quoted 5 lines

Is that change in behavior acceptable? A script that reads %(worktreepath) would now get a path for a branch that is being rebased. I think that is a fix, since the rest of Git already considers that branch checked out, but I would like to hear if anyone relies on the empty value.

I think we can consider the change in behavior to be a bug fix.

If we’re doing this in order to usefully feed it to worktree-remove, though, do you really want to remove a worktree that is mid-rebase? I would think that could have work you don’t want to throw away without considering. (Besides which, would it show up
in --merged=origin? Hm.)

I suppose I would expect remove to fail without a « force » flag if the worktree is mid-rebase, but still.

#14 lore raw

Re: [PATCH v2] worktree list: add --branch to select worktrees by branch

Quoted 15 lines · Ben Knoble
Quoted 7 lines · Phillip Wood

Hi Jasper

Quoted 1 line · Jasper Mayone
Quoted 7 lines
Quoted 5 lines

Is that change in behavior acceptable? A script that reads %(worktreepath) would now get a path for a branch that is being rebased. I think that is a fix, since the rest of Git already considers that branch checked out, but I would like to hear if anyone relies on the empty value.

I think we can consider the change in behavior to be a bug fix.

Quoted 8 lines

If we’re doing this in order to usefully feed it to worktree-remove, though, do you really want to remove a worktree that is mid-rebase? I would think that could have work you don’t want to throw away without considering. (Besides which, would it show up
in --merged=origin? Hm.)

I suppose I would expect remove to fail without a « force » flag if the worktree is mid-rebase, but still.

That's an interesting point. I agree "git worktree remove" shouldn't remove a worktree that's in the middle of a rebase or bisect. To me that is a bug in "git worktree remove" that is more likely to be triggered if we start reporting the worktree where branches are being rebased.

Thanks

Phillip

#15 lore raw

cover worktree: treat a branch being rebased or bisected as checked out

In reply to Jasper Mayone

This replaces my "git worktree list --branch" patch [1]. In that thread Kristoffer pointed out that "git for-each-ref --merged <commit> --format='%(worktreepath)' refs/heads/" already finds the worktrees of merged branches, so a new option is not needed. What is missing is that %(worktreepath) ignores a branch while a worktree is rebasing or bisecting it, although "git worktree add" and "git branch -d" already treat that branch as checked out. Phillip agreed that this is a bug.

Ben then asked what happens if such a worktree is passed to "git worktree remove". Today it is removed, and the rebase or bisect state is lost with it, if the files happen to be clean. Phillip called that a bug too, and more likely to be hit once %(worktreepath) reports these worktrees, so it is fixed first.

1/2 makes "git worktree remove" refuse a worktree in the middle of a
rebase, "git am", bisect, or cherry-pick or revert sequence, unless --force is given.

2/2 makes %(worktreepath), and so the "+" marker of "git branch",
name the worktree that is rebasing or bisecting a branch, as prepare_checked_out_branches() in branch.c does. Branches that "rebase --update-refs" will move are not included.

Two things reviewers may want to decide differently:

* In the worktree that is doing the rebase, "git branch" now shows both "* (no branch, rebasing topic)" and "+ topic". I documented that rather than special-case the current worktree in the format that "git branch" builds, because %(worktreepath) itself should not depend on where it is run. If you would rather hide the "+" there, I can do that in "git branch" instead.

* A merge stopped with --no-commit is not checked by 1/2. Its staged changes already make "git status" report the worktree as unclean in the common case.

[1] https://lore.kernel.org/git/[email protected]/

Jasper Mayone (2):
worktree remove: refuse a worktree in the middle of a rebase or bisect
ref-filter: name the worktree of a branch being rebased or bisected

 Documentation/git-branch.adoc       |  5 ++-
 Documentation/git-for-each-ref.adoc |  4 +-
 Documentation/git-worktree.adoc     | 11 +++--
 builtin/worktree.c                  | 31 +++++++++++++-
 ref-filter.c                        | 60 +++++++++++++++++++++------
 t/t2403-worktree-move.sh            | 59 +++++++++++++++++++++++++++
 t/t3203-branch-output.sh            | 35 ++++++++++++++++
 t/t6302-for-each-ref-filter.sh      | 63 +++++++++++++++++++++++++++++
 8 files changed, 249 insertions(+), 19 deletions(-)

base-commit: b9e5cff1803ab24582201ef059516eb16014b9d9

Signature · 1 line
2.56.0
#16 lore raw

PATCH 1/2 worktree remove: refuse a worktree in the middle of a rebase or bisect

"git worktree remove" refuses a worktree with modified or untracked files unless --force is given, but it removes a worktree that is in the middle of a rebase, a "git am" session, a bisect or a cherry-pick or revert sequence when its files happen to be clean. The state of that operation lives in the worktree's own $GIT_DIR, so it is lost with the worktree. A rebase stopped at an "edit" or "break" line, an "exec" that failed, or a cherry-pick sequence after a conflict was resolved and committed is clean in this sense and still has work in progress.

Treat such a worktree as unclean: refuse to remove it unless --force is given, and name the operation in the message.

A worktree whose directory is already gone is still removed without --force, as before: the check is part of the check for a clean worktree, which is only done when the directory exists.

---
 Documentation/git-worktree.adoc | 11 +++---
 builtin/worktree.c              | 31 ++++++++++++++++-
 t/t2403-worktree-move.sh        | 59 +++++++++++++++++++++++++++++++++
 3 files changed, 96 insertions(+), 5 deletions(-)
Documentation/git-worktree.adoc +7 -4
index e6e77252ab..da4c38f909 100644
@@ -142,9 +142,10 @@ the new working tree location.
 `remove`::
 
 Remove a worktree. Only clean worktrees (no untracked files and no
-modification in tracked files) can be removed. Unclean worktrees or ones
-with submodules can be removed with `--force`. The main worktree cannot be
-removed.
+modification in tracked files) can be removed. A worktree in the middle
+of a rebase, a `git am` session, a bisect or a cherry-pick or revert
+sequence is not clean either, because removing it loses that state. Unclean worktrees or ones with submodules
+can be removed with `--force`. The main worktree cannot be removed.
 
 `repair [<path>...]`::
 
@@ -189,7 +190,9 @@ twice. If the destination is already assigned to some other worktree but is
 missing (for instance, if _<new-path>_ was deleted manually), then `--force`
 allows the move to proceed; use `--force` twice if the destination is locked.
 +
-`remove` refuses to remove an unclean worktree unless `--force` is used.
+`remove` refuses to remove an unclean worktree, or one in the middle of a
+rebase, `git am` session, bisect, or cherry-pick or revert sequence,
+unless `--force` is used.
 To remove a locked worktree, specify `--force` twice.
 
 `-b <new-branch>`::
builtin/worktree.c +30 -1
index 77ecd0f71f..ed08de1f43 100644
@@ -26,6 +26,7 @@
 #include "submodule.h"
 #include "utf8.h"
 #include "worktree.h"
+#include "wt-status.h"
 #include "quote.h"
 
 #define BUILTIN_WORKTREE_ADD_USAGE \
@@ -1408,6 +1409,32 @@ static void check_clean_worktree(struct worktree *wt,
 			  original_path, ret);
 }
 
+/*
+ * A rebase, "git am", bisect or cherry-pick/revert sequence keeps its
+ * state in the worktree's own $GIT_DIR, and removing the worktree
+ * throws that away even when "git status" says the files are clean.
+ */
+static void check_no_operation_in_progress(struct worktree *wt,
+					   const char *original_path)
+{
+	struct wt_status_state state = { 0 };
+
+	if (wt_status_check_rebase(wt, &state)) {
+		if (state.am_in_progress)
+			die(_("'%s' is in the middle of an am session, use --force to delete it"),
+			    original_path);
+		die(_("'%s' is in the middle of a rebase, use --force to delete it"),
+		    original_path);
+	}
+	if (wt_status_check_bisect(wt, &state))
+		die(_("'%s' is in the middle of a bisect, use --force to delete it"),
+		    original_path);
+	wt_status_state_free_buffers(&state);
+	if (is_directory(worktree_git_path(wt, "sequencer")))
+		die(_("'%s' is in the middle of a cherry-pick or revert, use --force to delete it"),
+		    original_path);
+}
+
 static int delete_git_work_tree(struct worktree *wt)
 {
 	struct strbuf sb = STRBUF_INIT;
@@ -1461,8 +1488,10 @@ static int remove_worktree(int ac, const char **av, const char *prefix,
 	strbuf_release(&errmsg);
 
 	if (file_exists(wt->path)) {
-		if (!force)
+		if (!force) {
+			check_no_operation_in_progress(wt, av[0]);
 			check_clean_worktree(wt, av[0]);
+		}
 
 		ret |= delete_git_work_tree(wt);
 	}
t/t2403-worktree-move.sh +59 -0

63 lines not on this page · raw message

Signature · 1 line
2.56.0
#17 lore raw

Re: [PATCH 1/2] worktree remove: refuse a worktree in the middle of a rebase or bisect

Hi Jasper

Quoted 1 line · Jasper Mayone

"git worktree remove" refuses a worktree with modified or untracked

"refuses to move" would be clearer

Quoted 8 lines

files unless --force is given, but it removes a worktree that is in the middle of a rebase, a "git am" session, a bisect or a cherry-pick or revert sequence when its files happen to be clean. The state of that operation lives in the worktree's own $GIT_DIR, so it is lost with the worktree. A rebase stopped at an "edit" or "break" line, an "exec" that failed, or a cherry-pick sequence after a conflict was resolved and committed is clean in this sense and still has work in progress.

Cherry picking or reverting a single commit that contains no new changes also looks clean, but there is still a cherry-pick operation in progress as CHERRY_PICK_HEAD exists. One could argue that, because the user doesn't really lose any work, we don't lose much by deleting such a worktree but we're still deleting a worktree that contains an in-progress operation. Fixing that case simply requires us to see if CHERRY_PICK_HEAD, or REVERT_HEAD exist.

Quoted 6 lines

Treat such a worktree as unclean: refuse to remove it unless --force is given, and name the operation in the message.

A worktree whose directory is already gone is still removed without --force, as before: the check is part of the check for a clean worktree, which is only done when the directory exists.

Sensible

Quoted 2 lines

I'm not sure what I've done anything to help with this patch

Documentation/git-worktree.adoc the new working tree location. · line 146

Quoted 13 lines
Documentation/git-worktree.adoc +2 -3
index e6e77252ab..da4c38f909 100644
@@ -142,9 +142,10 @@ the new working tree location.
  `remove`::
 
  Remove a worktree. Only clean worktrees (no untracked files and no
-modification in tracked files) can be removed. Unclean worktrees or ones
-with submodules can be removed with `--force`. The main worktree cannot be
-removed.
+modification in tracked files) can be removed. A worktree in the middle
+of a rebase, a `git am` session, a bisect or a cherry-pick or revert

"bisect, cherry-pick or revert"

Documentation/git-worktree.adoc the new working tree location. · line 147

Quoted 1 line
Documentation/git-worktree.adoc +1 -0
+sequence is not clean either, 

"either" doesn't make sense, because you've not described the unclean case yet. This line needs folding as well.

Quoted 2 lines

because removing it loses that state. Unclean worktrees or ones with submodules +can be removed with --force. The main worktree cannot be removed.

A list of the conditions that require --force might make this section clearer.

Documentation/git-worktree.adoc twice. If the destination is already assigned to some other worktree but is · line 194

Quoted 9 lines

repair [<path>...]::

Documentation/git-worktree.adoc +2 -1
@@ -189,7 +190,9 @@ twice. If the destination is already assigned to some other worktree but is
  missing (for instance, if _<new-path>_ was deleted manually), then `--force`
  allows the move to proceed; use `--force` twice if the destination is locked.
  +
-`remove` refuses to remove an unclean worktree unless `--force` is used.
+`remove` refuses to remove an unclean worktree, or one in the middle of a
+rebase, `git am` session, bisect, or cherry-pick or revert sequence,

too many "or"s as above

Quoted 35 lines
Documentation/git-worktree.adoc +1 -0
+unless `--force` is used.
  To remove a locked worktree, specify `--force` twice.
 
  `-b <new-branch>`::
builtin/worktree.c +16 -0
index 77ecd0f71f..ed08de1f43 100644
@@ -26,6 +26,7 @@
  #include "submodule.h"
  #include "utf8.h"
  #include "worktree.h"
+#include "wt-status.h"
  #include "quote.h"
 
  #define BUILTIN_WORKTREE_ADD_USAGE \
@@ -1408,6 +1409,32 @@ static void check_clean_worktree(struct worktree *wt,
  			  original_path, ret);
  }
 
+/*
+ * A rebase, "git am", bisect or cherry-pick/revert sequence keeps its
+ * state in the worktree's own $GIT_DIR, and removing the worktree
+ * throws that away even when "git status" says the files are clean.
+ */
+static void check_no_operation_in_progress(struct worktree *wt,
+					   const char *original_path)
+{
+	struct wt_status_state state = { 0 };
+
+	if (wt_status_check_rebase(wt, &state)) {
+		if (state.am_in_progress)
+			die(_("'%s' is in the middle of an am session, use --force to delete it"),
+			    original_path);
+		die(_("'%s' is in the middle of a rebase, use --force to delete it"),

builtin/worktree.c static void check_clean_worktree(struct worktree *wt, · line 1436

Quoted 10 lines
builtin/worktree.c +10 -0
+		    original_path);
+	}
+	if (wt_status_check_bisect(wt, &state))
+		die(_("'%s' is in the middle of a bisect, use --force to delete it"),
+		    original_path);
+	wt_status_state_free_buffers(&state);
+	if (is_directory(worktree_git_path(wt, "sequencer")))
+		die(_("'%s' is in the middle of a cherry-pick or revert, use --force to delete it"),
+		    original_path);
+}

This looks correct, though I wish we had a standard function that returned an enum describing which operation was in progress, rather than having to open code this sort of thing.

builtin/worktree.c static int remove_worktree(int ac, const char **av, const char *prefix, · line 1492

Quoted 10 lines
builtin/worktree.c +2 -1
  static int delete_git_work_tree(struct worktree *wt)
  {
  	struct strbuf sb = STRBUF_INIT;
@@ -1461,8 +1488,10 @@ static int remove_worktree(int ac, const char **av, const char *prefix,
  	strbuf_release(&errmsg);
 
  	if (file_exists(wt->path)) {
-		if (!force)
+		if (!force) {
+			check_no_operation_in_progress(wt, av[0]);

This triggers the new check when the worktree directory exists - good.

Quoted 26 lines
builtin/worktree.c +1 -0
  			check_clean_worktree(wt, av[0]);
+		}
 
  		ret |= delete_git_work_tree(wt);
  	}
t/t2403-worktree-move.sh +13 -0
index 69768c1207..4eb56a8911 100755
@@ -271,4 +271,63 @@ test_expect_success 'move worktree with relative path to absolute path' '
  	test_cmp expect .git/worktrees/absolute/gitdir
  '
 
+test_expect_success 'remove worktree in the middle of a rebase' '
+	test_when_finished "rm -rf mid-rebase; git worktree prune" &&
+	git worktree add --detach mid-rebase init &&
+	test_commit -C mid-rebase rebase-me &&
+	test_must_fail git -C mid-rebase rebase -f -x false init &&
+	test_must_fail git worktree remove mid-rebase 2>err &&
+	test_grep "in the middle of a rebase" err &&
+	test_path_is_dir mid-rebase &&
+	git worktree remove --force mid-rebase &&
+	test_path_is_missing mid-rebase
+'
+
+test_expect_success 'remove worktree in the middle of an am session' '

t/t2403-worktree-move.sh test_expect_success 'move worktree with relative path to absolute path' ' · line 296

Quoted 10 lines
t/t2403-worktree-move.sh +10 -0
+	test_when_finished "rm -rf mid-am patch; git worktree prune" &&
+	git worktree add --detach mid-am init &&
+	test_commit -C mid-am am-me &&
+	git -C mid-am format-patch -1 --stdout >patch &&
+	git -C mid-am reset --hard init &&
+	echo conflict >mid-am/am-me.t &&
+	git -C mid-am add am-me.t &&
+	git -C mid-am commit -m conflict &&
+	test_must_fail git -C mid-am am ../patch &&
+	git -C mid-am reset --hard &&

If we're running a lot of consecutive commands in a worktree, it is clearer to use a subshell

	(
		cd mid-am &&
		...
	) &&

I wonder how hard it would be to extend the "setup" test to create a branch that has conflicts when it is applied with am, cherry-pick, or rebase, so that we don't have to set up the conflicts in each test.

Thanks

Phillip

Quoted 37 lines
t/t2403-worktree-move.sh +36 -0
+	test_must_fail git worktree remove mid-am 2>err &&
+	test_grep "in the middle of an am session" err &&
+	git worktree remove --force mid-am
+'
+
+test_expect_success 'remove worktree in the middle of a bisect' '
+	test_when_finished "rm -rf mid-bisect; git worktree prune" &&
+	git worktree add --detach mid-bisect init &&
+	test_commit -C mid-bisect bisect-one &&
+	test_commit -C mid-bisect bisect-two &&
+	git -C mid-bisect bisect start HEAD init &&
+	test_must_fail git worktree remove mid-bisect 2>err &&
+	test_grep "in the middle of a bisect" err &&
+	git worktree remove --force mid-bisect
+'
+
+test_expect_success 'remove worktree in the middle of a cherry-pick sequence' '
+	test_when_finished "rm -rf mid-pick; git worktree prune" &&
+	git worktree add --detach mid-pick init &&
+	git -C mid-pick switch -c pick-src &&
+	test_commit -C mid-pick pick-one &&
+	test_commit -C mid-pick pick-two &&
+	git -C mid-pick switch --detach init &&
+	echo conflict >mid-pick/pick-one.t &&
+	git -C mid-pick add pick-one.t &&
+	git -C mid-pick commit -m conflict &&
+	test_must_fail git -C mid-pick cherry-pick pick-src~1 pick-src &&
+	git -C mid-pick checkout --theirs pick-one.t &&
+	git -C mid-pick add pick-one.t &&
+	git -C mid-pick commit --no-edit &&
+	test_path_is_dir .git/worktrees/mid-pick/sequencer &&
+	test_must_fail git worktree remove mid-pick 2>err &&
+	test_grep "in the middle of a cherry-pick or revert" err &&
+	git worktree remove --force mid-pick
+'
+
  test_done
#18 lore raw

Re: [PATCH 1/2] worktree remove: refuse a worktree in the middle of a rebase or bisect

Quoted 3 lines · Phillip Wood

Cherry picking or reverting a single commit that contains no new changes also looks clean, but there is still a cherry-pick operation in progress as CHERRY_PICK_HEAD exists.

[...]

Quoted 2 lines

Fixing that case simply requires us to see if CHERRY_PICK_HEAD, or REVERT_HEAD exist.

Good catch. v4 will check for CHERRY_PICK_HEAD and REVERT_HEAD in the worktree's $GIT_DIR as well as the sequencer directory, with a test for a single empty cherry-pick.

Quoted 3 lines
Quoted 1 line

I'm not sure what I've done anything to help with this patch

You are right, your help was on the other patch. I will drop it here.

Quoted 2 lines

A list of the conditions that require --force might make this section clearer.

Agreed. I will turn the remove description into a list of what makes a worktree unclean (modified or untracked files, submodules, and an operation in progress), and fix the "or" chains and "either" you pointed out.

Quoted 2 lines

If we're running a lot of consecutive commands in a worktree, it is clearer to use a subshell

Will do.

Quoted 3 lines

I wonder how hard it would be to extend the "setup" test to create a branch that has conflicts when it is applied with am, cherry-pick, or rebase, so that we don't have to set up the conflicts in each test.

I will try that for v4. A branch that changes the same line as a commit on top of "init" should give a conflict for all three.

Thanks for the review.

Jasper

#19 lore raw

PATCH 2/2 ref-filter: name the worktree of a branch being rebased or bisected

In reply to Jasper Mayone

%(worktreepath) gives the worktree that has a branch checked out, and "git branch" uses it to mark such branches with "+". It only looks at the HEAD of each worktree, so while a worktree is rebasing or bisecting a branch, its HEAD is detached and the branch shows no worktree at all.

The rest of Git already treats that branch as checked out: "git worktree add" and "git branch -d" refuse it, because finishing the rebase or bisect will check it out again. "git worktree list" shows such a worktree as "(detached HEAD)", so %(worktreepath) is the only place a script could find out which worktree is working on the branch.

Also map the branch that a worktree is rebasing or bisecting to that worktree, as prepare_checked_out_branches() in branch.c does. Branches that "rebase --update-refs" will update are not mapped: that worktree has not checked them out, it only moves them when the rebase is done.

As a result "git branch" marks such a branch with "+", also when it runs in the worktree that is rebasing or bisecting it, where it shows both "* (no branch, rebasing topic)" and "+ topic". Document that.

---
 Documentation/git-branch.adoc       |  5 ++-
 Documentation/git-for-each-ref.adoc |  4 +-
 ref-filter.c                        | 60 +++++++++++++++++++++------
 t/t3203-branch-output.sh            | 35 ++++++++++++++++
 t/t6302-for-each-ref-filter.sh      | 63 +++++++++++++++++++++++++++++
 5 files changed, 153 insertions(+), 14 deletions(-)
Documentation/git-branch.adoc +4 -1
index bfdf459329..d499d7e0d4 100644
@@ -33,7 +33,10 @@ DESCRIPTION
 If `--list` is given, or if there are no non-option arguments, existing
 branches are listed; the current branch will be highlighted in green and
 marked with an asterisk.  Any branches checked out in linked worktrees will
-be highlighted in cyan and marked with a plus sign. Option `-r` causes the
+be highlighted in cyan and marked with a plus sign. A branch that a
+worktree is rebasing or bisecting counts as checked out there, so it is
+marked in the same way, also in the worktree that is rebasing or
+bisecting it. Option `-r` causes the
 remote-tracking branches to be listed,
 and option `-a` shows both local and remote branches.
 
Documentation/git-for-each-ref.adoc +3 -1
index a7b31e8aaf..90ff37259e 100644
@@ -182,7 +182,9 @@ but if used together the last option is selected.
 
 `worktreepath`::
 	The absolute path to the worktree in which the ref is checked
-	out, if it is checked out in any linked worktree. Empty string
+	out, if it is checked out in any linked worktree. A branch that
+	a worktree is rebasing or bisecting counts as checked out there,
+	although that worktree's `HEAD` is detached. Empty string
 	otherwise.
 
 `ahead-behind:<commit-ish>`::
ref-filter.c +48 -12

84 lines not on this page · raw message

t/t3203-branch-output.sh +35 -0
index 7c44186341..e04599392d 100755
@@ -442,6 +442,41 @@ test_expect_success 'worktree colors correct' '
 	test_cmp expect actual
 '
 
+test_expect_success 'branch being rebased in a worktree is marked' '
+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebase_dir branch-two &&
+	git -C rebase_dir commit --allow-empty -m rebase-me &&
+	test_must_fail git -C rebase_dir rebase -f -x false HEAD~1 &&
+	test_must_fail git -C rebase_dir symbolic-ref -q HEAD &&
+	git branch --list rebasing >actual &&
+	echo "+ rebasing" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success 'branch being rebased is marked in its own worktree' '
+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebase_dir branch-two &&
+	git -C rebase_dir commit --allow-empty -m rebase-me &&
+	test_must_fail git -C rebase_dir rebase -f -x false HEAD~1 &&
+	git -C rebase_dir branch --list rebasing >actual &&
+	echo "+ rebasing" >expect &&
+	test_cmp expect actual &&
+	git -C rebase_dir branch >actual &&
+	test_grep "^\* (no branch, rebasing rebasing)" actual
+'
+
+test_expect_success 'branch being bisected in a worktree is marked' '
+	test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
+	git worktree add -b bisecting bisect_dir branch-two &&
+	git -C bisect_dir commit --allow-empty -m bisect-one &&
+	git -C bisect_dir commit --allow-empty -m bisect-two &&
+	git -C bisect_dir bisect start HEAD HEAD~2 &&
+	test_must_fail git -C bisect_dir symbolic-ref -q HEAD &&
+	git branch --list bisecting >actual &&
+	echo "+ bisecting" >expect &&
+	test_cmp expect actual
+'
+
 test_expect_success "set up color tests" '
 	echo "<RED>main<RESET>" >expect.color &&
 	echo "main" >expect.bare &&
t/t6302-for-each-ref-filter.sh +63 -0

75 lines not on this page · raw message

Signature · 1 line
2.56.0
#20 lore raw

Re: [PATCH 2/2] ref-filter: name the worktree of a branch being rebased or bisected

Hi Jasper

Quoted 9 lines · Jasper Mayone

%(worktreepath) gives the worktree that has a branch checked out, and "git branch" uses it to mark such branches with "+". It only looks at the HEAD of each worktree, so while a worktree is rebasing or bisecting a branch, its HEAD is detached and the branch shows no worktree at all.

The rest of Git already treats that branch as checked out: "git worktree add" and "git branch -d" refuse it, because finishing the rebase or bisect will check it out again.

Those commands also reject branches that are being updated by a rebase via "update-ref" commands. If we're interested in checkouts we don't want to list those, but it means that "%(worktree)" will still give different results.

Quoted 4 lines

"git worktree list" shows
such a worktree as "(detached HEAD)", so %(worktreepath) is the only place a script could find out which worktree is working on the branch.

I don't really follow this logic. At the moment neither "git for-each-ref", nor "git worktree list" show this - there is no way for a script to find out which worktree is working on a given branch. We can choose to add it to one or both commands.

Quoted 2 lines

Also map the branch that a worktree is rebasing or bisecting to that worktree, as prepare_checked_out_branches() in branch.c does.

If we want it to behave like prepare_checked_out_branches() we should use that function, rather than copying some of it to a separate file. If we want to only list checked out branches we could do as I previously suggested and add a function to branch.c that lists the worktrees where a branch is checked out.

Quoted 3 lines

Branches that "rebase --update-refs" will update are not mapped: that worktree has not checked them out, it only moves them when the rebase is done.

I think that's sensible

Quoted 3 lines

As a result "git branch" marks such a branch with "+", also when it runs in the worktree that is rebasing or bisecting it, where it shows both "* (no branch, rebasing topic)" and "+ topic". Document that.

That sounds a bit confusing - "* (no branch, rebasing topic)" already tells us what we need to know, why do we need "+ topic" as well? The output of git branch is intended for human consumption, not scripts.

Documentation/git-branch.adoc DESCRIPTION · line 38

Quoted 12 lines
Documentation/git-branch.adoc +3 -1
index bfdf459329..d499d7e0d4 100644
@@ -33,7 +33,10 @@ DESCRIPTION
  If `--list` is given, or if there are no non-option arguments, existing
  branches are listed; the current branch will be highlighted in green and
  marked with an asterisk.  Any branches checked out in linked worktrees will
-be highlighted in cyan and marked with a plus sign. Option `-r` causes the
+be highlighted in cyan and marked with a plus sign. A branch that a
+worktree is rebasing or bisecting counts as checked out there, so it is
+marked in the same way,

I follow this up to here

Quoted 1 line

also in the worktree that is rebasing or bisecting it.

but what is this trying to say?

Documentation/git-for-each-ref.adoc but if used together the last option is selected. · line 188

Quoted 13 lines
Documentation/git-for-each-ref.adoc +3 -1
index a7b31e8aaf..90ff37259e 100644
@@ -182,7 +182,9 @@ but if used together the last option is selected.
 
  `worktreepath`::
  	The absolute path to the worktree in which the ref is checked
-	out, if it is checked out in any linked worktree. Empty string
+	out, if it is checked out in any linked worktree. A branch that
+	a worktree is rebasing or bisecting counts as checked out there,
+	although that worktree's `HEAD` is detached. Empty string
  	otherwise.

It is not a new problem, but I think it would be helpful to add something like

As the path may contain a newline, it is recommended to either use one of the quoting options, or follow %(worktreepath) with %00 and parse the output by looking for the NUL after the worktree path and then the LF that terminates each output record.

Note that if a branch checked out in more than one worktree, %(worktreepath) will only show one of those worktrees.

Quoted 20 lines
ref-filter.c +7 -5
index bdf54f6f59..1aebea243e 100644
[...]
+/*
+ * Map each branch to the worktree that has it checked out. A worktree
+ * that is rebasing or bisecting a branch has it checked out, too,
+ * even though its HEAD may be detached, as for
+ * prepare_checked_out_branches() in branch.c.
+ */
  static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
  {
-	int i;
+	struct strbuf ref = STRBUF_INIT;
 
-	for (i = 0; worktrees[i]; i++) {
-		if (worktrees[i]->head_ref) {
-			struct ref_to_worktree_entry *entry;
-			entry = xmalloc(sizeof(*entry));

ref-filter.c static int get_object(struct ref_array_item *ref, int deref, · line 2410

Quoted 10 lines
ref-filter.c +5 -4
-			entry->wt = worktrees[i];
-			hashmap_entry_init(&entry->ent,
-					strhash(worktrees[i]->head_ref));
+	for (size_t i = 0; worktrees[i]; i++) {
+		struct worktree *wt = worktrees[i];
+		struct wt_status_state state = { 0 };
 
-			hashmap_add(map, &entry->ent);
+		if (wt->is_bare)
+			continue;

This is a change in behavior. We currently print the git_dir of bare worktrees. I think you can argue that this change is a bug fix as the user asked for the worktree path, but it should be explained in the commit message.

It is a shame that we end up duplicating code that is already in branch.c. As I said last time, I think that it would be better to have a single implementation that maps branches to worktrees in branch.c and call that function rather than duplicating it here.

Thanks

Phillip

Quoted 153 lines
ref-filter.c +21 -0
+
+		if (wt->head_ref)
+			add_worktree_entry(map, wt, wt->head_ref);
+
+		if (wt_status_check_rebase(wt, &state) &&
+		    (state.rebase_in_progress ||
+		     state.rebase_interactive_in_progress) &&
+		    state.branch) {
+			strbuf_reset(&ref);
+			strbuf_addf(&ref, "refs/heads/%s", state.branch);
+			add_worktree_entry(map, wt, ref.buf);
  		}
+		wt_status_state_free_buffers(&state);
+
+		if (wt_status_check_bisect(wt, &state) &&
+		    state.bisecting_from) {
+			strbuf_reset(&ref);
+			strbuf_addf(&ref, "refs/heads/%s", state.bisecting_from);
+			add_worktree_entry(map, wt, ref.buf);
+		}
+		wt_status_state_free_buffers(&state);
  	}
+	strbuf_release(&ref);
  }
 
  static void lazy_init_worktree_map(void)
t/t3203-branch-output.sh +35 -0
index 7c44186341..e04599392d 100755
@@ -442,6 +442,41 @@ test_expect_success 'worktree colors correct' '
  	test_cmp expect actual
  '
 
+test_expect_success 'branch being rebased in a worktree is marked' '
+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebase_dir branch-two &&
+	git -C rebase_dir commit --allow-empty -m rebase-me &&
+	test_must_fail git -C rebase_dir rebase -f -x false HEAD~1 &&
+	test_must_fail git -C rebase_dir symbolic-ref -q HEAD &&
+	git branch --list rebasing >actual &&
+	echo "+ rebasing" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success 'branch being rebased is marked in its own worktree' '
+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebase_dir branch-two &&
+	git -C rebase_dir commit --allow-empty -m rebase-me &&
+	test_must_fail git -C rebase_dir rebase -f -x false HEAD~1 &&
+	git -C rebase_dir branch --list rebasing >actual &&
+	echo "+ rebasing" >expect &&
+	test_cmp expect actual &&
+	git -C rebase_dir branch >actual &&
+	test_grep "^\* (no branch, rebasing rebasing)" actual
+'
+
+test_expect_success 'branch being bisected in a worktree is marked' '
+	test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
+	git worktree add -b bisecting bisect_dir branch-two &&
+	git -C bisect_dir commit --allow-empty -m bisect-one &&
+	git -C bisect_dir commit --allow-empty -m bisect-two &&
+	git -C bisect_dir bisect start HEAD HEAD~2 &&
+	test_must_fail git -C bisect_dir symbolic-ref -q HEAD &&
+	git branch --list bisecting >actual &&
+	echo "+ bisecting" >expect &&
+	test_cmp expect actual
+'
+
  test_expect_success "set up color tests" '
  	echo "<RED>main<RESET>" >expect.color &&
  	echo "main" >expect.bare &&
t/t6302-for-each-ref-filter.sh +63 -0
index 7f060d97bf..d656901f21 100755
@@ -3,6 +3,7 @@
  test_description='test for-each-refs usage of ref-filter APIs'
 
  . ./test-lib.sh
+. "$TEST_DIRECTORY"/lib-rebase.sh
  . "$TEST_DIRECTORY"/lib-gpg.sh
 
  test_expect_success 'setup some history and refs' '
@@ -541,6 +542,68 @@ test_expect_success 'validate worktree atom' '
  	test_cmp expect actual
  '
 
+test_expect_success 'worktree atom names a worktree rebasing the branch' '
+	test_when_finished "git -C rebasing rebase --abort; rm -rf rebasing; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebasing main &&
+	git -C rebasing commit --allow-empty -m rebase-me &&
+	test_must_fail git -C rebasing rebase -f -x false main &&
+	test_must_fail git -C rebasing symbolic-ref -q HEAD &&
+	echo "$(pwd)/rebasing" >expect &&
+	git for-each-ref --format="%(worktreepath)" refs/heads/rebasing >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'worktree atom names a worktree bisecting the branch' '
+	test_when_finished "git -C bisecting bisect reset; rm -rf bisecting; git worktree prune; git branch -D bisecting" &&
+	git worktree add -b bisecting bisecting main &&
+	git -C bisecting commit --allow-empty -m bisect-one &&
+	git -C bisecting commit --allow-empty -m bisect-two &&
+	git -C bisecting bisect start HEAD main &&
+	test_must_fail git -C bisecting symbolic-ref -q HEAD &&
+	echo "$(pwd)/bisecting" >expect &&
+	git for-each-ref --format="%(worktreepath)" refs/heads/bisecting >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'worktree atom with an interactive rebase stopped at edit' '
+	test_when_finished "git -C editing rebase --abort; rm -rf editing; git worktree prune; git branch -D editing" &&
+	git worktree add -b editing editing main &&
+	git -C editing commit --allow-empty -m edit-me &&
+	(
+		set_fake_editor &&
+		FAKE_LINES="edit 1" git -C editing rebase -i --keep-empty HEAD~1
+	) &&
+	test_must_fail git -C editing symbolic-ref -q HEAD &&
+	echo "$(pwd)/editing" >expect &&
+	git for-each-ref --format="%(worktreepath)" refs/heads/editing >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'worktree atom ignores branches rebase --update-refs will move' '
+	test_when_finished "git -C updating rebase --abort; rm -rf updating; git worktree prune; git branch -D updating mid" &&
+	git worktree add -b updating updating main &&
+	git -C updating commit --allow-empty -m one &&
+	git -C updating branch mid &&
+	git -C updating commit --allow-empty -m two &&
+	test_must_fail git -C updating rebase -f --update-refs -x false main &&
+	git for-each-ref --format="%(refname:short) [%(worktreepath)]" \
+		refs/heads/updating refs/heads/mid >actual &&
+	cat >expect <<-EOF &&
+	mid []
+	updating [$(pwd)/updating]
+	EOF
+	test_cmp expect actual
+'
+
+test_expect_success 'worktree atom ignores a rebase of a detached HEAD' '
+	test_when_finished "git -C detached-rebase rebase --abort; rm -rf detached-rebase; git worktree prune" &&
+	git worktree add --detach detached-rebase main &&
+	git -C detached-rebase commit --allow-empty -m detached &&
+	test_must_fail git -C detached-rebase rebase -f -x false main &&
+	git for-each-ref --format="%(worktreepath)" refs/heads/ >actual &&
+	test_grep ! detached-rebase actual
+'
+
  test_expect_success 'start after with empty value' '
  	cat >expect <<-\EOF &&
  	refs/heads/main
#21 lore raw

Re: [PATCH 2/2] ref-filter: name the worktree of a branch being rebased or bisected

Quoted 4 lines · Phillip Wood

Those commands also reject branches that are being updated by a rebase via "update-ref" commands. If we're interested in checkouts we don't want to list those, but it means that "%(worktree)" will still give different results.

Yes, that difference is on purpose. I will say so in the commit message and the documentation.

Quoted 4 lines

I don't really follow this logic. At the moment neither "git for-each-ref", nor "git worktree list" show this - there is no way for a script to find out which worktree is working on a given branch. We can choose to add it to one or both commands.

You are right, that paragraph is wrong. No command shows it today, and this patch adds it to %(worktreepath) only. I will rewrite it.

Quoted 2 lines

If we want it to behave like prepare_checked_out_branches() we should use that function, rather than copying some of it to a separate file.

Agreed. For v4 I have added a small function to branch.c,

    const char *branch_checked_out_worktree(const char *refname);

which reads the list that prepare_checked_out_branches() builds and skips the BRANCH_CHECKOUT_KIND_UPDATE_REF entries. ref-filter calls it and drops its own hashmap, so the patch now removes more code than it adds in ref-filter.c. t6302, t3203, t3200, t2400 and t2403 pass with it.

Quoted 2 lines

That sounds a bit confusing - "* (no branch, rebasing topic)" already tells us what we need to know, why do we need "+ topic" as well?

I agree. In v4 "git branch" will not mark the branch with "+" in the worktree that is rebasing or bisecting it, since the "*" line already names it. The "also in the worktree" sentence in git-branch.adoc goes away with that.

Quoted 7 lines

It is not a new problem, but I think it would be helpful to add something like

As the path may contain a newline, [...]

Note that if a branch checked out in more than one worktree, %(worktreepath) will only show one of those worktrees.

Thanks, I will add that as a separate documentation patch before this one.

Quoted 7 lines

ref-filter.c static int get_object(struct ref_array_item *ref, int deref, · line 2410

Quoted 2 lines
ref-filter.c +2 -0
+		if (wt->is_bare)
+			continue;

This is a change in behavior. We currently print the git_dir of bare worktrees. I think you can argue that this change is a bug fix as the user asked for the worktree path, but it should be explained in the commit message.

Agreed. With a bare repository and a linked worktree, today "git branch" in the linked worktree shows "+ main" for the bare repository's HEAD, and %(worktreepath) gives the path of the bare repository. main is not checked out anywhere, and "git worktree add" already lets you check it out. I will explain that in the commit message and add a test for it.

Thanks,
Jasper

#22 lore raw

Re: [PATCH 0/2] worktree: treat a branch being rebased or bisected as checked out

In reply to Jasper Mayone
Quoted 1 line · Jasper Mayone

This replaces my "git worktree list --branch" patch [1].

Then please label it as v3 as the old one is v2, or it breaks automation.

Quoted 8 lines

In that
thread Kristoffer pointed out that "git for-each-ref --merged <commit> --format='%(worktreepath)' refs/heads/" already finds the worktrees of merged branches, so a new option is not needed. What is missing is that %(worktreepath) ignores a branch while a worktree is rebasing or bisecting it, although "git worktree add" and "git branch -d" already treat that branch as checked out. Phillip agreed that this is a bug.

Quoted 5 lines

Ben then asked what happens if such a worktree is passed to "git worktree remove". Today it is removed, and the rebase or bisect state is lost with it, if the files happen to be clean. Phillip called that a bug too, and more likely to be hit once %(worktreepath) reports these worktrees, so it is fixed first.

All of these address great points. Thanks for working on it.

#23 lore raw

Re: [PATCH 0/2] worktree: treat a branch being rebased or bisected as checked out

Quoted 6 lines · Junio C Hamano
Quoted 1 line · Jasper Mayone

This replaces my "git worktree list --branch" patch [1].

Then please label it as v3 as the old one is v2, or it breaks automation.

Sorry about that. I will treat this round as v3, and the next round will be v4.

Quoted 1 line

All of these address great points. Thanks for working on it.

Thanks.

Jasper

#24 lore raw

v4 cover worktree: treat a branch being rebased or bisected as checked out

In reply to Jasper Mayone

While a worktree is rebasing or bisecting a branch, its HEAD is detached. "git worktree add" and "git branch -d" already treat the branch as checked out there, but "git worktree remove" deletes such a worktree when its files are clean, and %(worktreepath) and "git branch" do not show which worktree has the branch.

Patch 1 makes "git worktree remove" refuse a worktree in the middle of an operation unless --force is given. Patch 2 documents how to read %(worktreepath) safely. Patch 3 makes %(worktreepath) name the worktree that is rebasing or bisecting a branch, and patch 4 keeps "git branch" from marking that branch with "+" in that worktree.

Changes since v3 [1]:

* Patch 1: also refuse a worktree that has CHERRY_PICK_HEAD or REVERT_HEAD, for a single cherry-pick or revert whose files are clean, with tests. The git-worktree documentation now lists the cases that need --force. The tests use a shared setup and subshells. Dropped the Helped-by trailer, as Phillip asked.

* Patch 2 is new. It adds the notes that Phillip suggested to the documentation of %(worktreepath): the path can contain a newline, and only one worktree is shown for a branch that is checked out in more than one.

* Patch 3: %(worktreepath) now uses a new branch.c function, branch_checked_out_worktree(), that reads the list that prepare_checked_out_branches() builds, in place of a copy of that code in ref-filter.c. ref-filter.c loses its own worktree map. The commit message explains why branches that "rebase --update-refs" will update are not included, and the change for the HEAD of a bare repository, which now has a test.

* Patch 4 is new. "git branch" no longer marks a branch with "+" in the worktree that is rebasing or bisecting it, because the "(no branch, ...)" line already names it.

[1] https://lore.kernel.org/git/[email protected]/

Jasper Mayone (4):
worktree remove: refuse a worktree in the middle of an operation
doc: for-each-ref: say how to read %(worktreepath) safely
ref-filter: name the worktree of a branch being rebased or bisected
branch: do not mark the branch the current worktree is rebasing

 Documentation/git-branch.adoc       |   6 +-
 Documentation/git-for-each-ref.adoc |  12 +++-
 Documentation/git-worktree.adoc     |  17 +++--
 branch.c                            |  13 ++++
 branch.h                            |   9 +++
 builtin/branch.c                    | 103 +++++++++++++++++++++-------
 builtin/worktree.c                  |  37 +++++++++-
 ref-filter.c                        |  74 +-------------------
 t/t2403-worktree-move.sh            |  94 +++++++++++++++++++++++++
 t/t3203-branch-output.sh            |  49 +++++++++++++
 t/t6302-for-each-ref-filter.sh      |  76 ++++++++++++++++++++
 11 files changed, 386 insertions(+), 104 deletions(-)

Range-diff against v3:
1: a79b69a0e4 ! 1: bca692b844 worktree remove: refuse a worktree in the middle of a rebase or bisect

    @@ Metadata
     Author: Jasper Mayone <[email protected]>
     
      ## Commit message ##
    -    worktree remove: refuse a worktree in the middle of a rebase or bisect
    +    worktree remove: refuse a worktree in the middle of an operation
     
    -    "git worktree remove" refuses a worktree with modified or untracked
    -    files unless --force is given, but it removes a worktree that is in
    -    the middle of a rebase, a "git am" session, a bisect or a cherry-pick
    -    or revert sequence when its files happen to be clean. The state of
    -    that operation lives in the worktree's own $GIT_DIR, so it is lost
    -    with the worktree. A rebase stopped at an "edit" or "break" line, an
    -    "exec" that failed, or a cherry-pick sequence after a conflict was
    -    resolved and committed is clean in this sense and still has work in
    -    progress.
    +    "git worktree remove" refuses to remove a worktree with modified or
    +    untracked files unless --force is given, but it removes a worktree
    +    that is in the middle of a rebase, a "git am" session, a bisect, a
    +    cherry-pick or a revert when its files happen to be clean. The state
    +    of that operation lives in the worktree's own $GIT_DIR, so it is lost
    +    with the worktree. Examples of such a clean worktree are a rebase
    +    stopped at an "edit" or "break" line or after a failed "exec", a
    +    cherry-pick sequence after a conflict was resolved and committed, and
    +    a single cherry-pick or revert whose conflict was resolved to the
    +    current contents, which leaves CHERRY_PICK_HEAD or REVERT_HEAD behind.
     
         Treat such a worktree as unclean: refuse to remove it unless --force
         is given, and name the operation in the message.
    @@ Commit message
         worktree, which is only done when the directory exists.
     
         Reported-by: D. Ben Knoble <[email protected]>
    -    Helped-by: Phillip Wood <[email protected]>
         Signed-off-by: Jasper Mayone <[email protected]>
     
      ## Documentation/git-worktree.adoc ##
     @@ Documentation/git-worktree.adoc: the new working tree location.
    + 
      `remove`::
      
    - Remove a worktree. Only clean worktrees (no untracked files and no
    +-Remove a worktree. Only clean worktrees (no untracked files and no
     -modification in tracked files) can be removed. Unclean worktrees or ones
     -with submodules can be removed with `--force`. The main worktree cannot be
     -removed.
    -+modification in tracked files) can be removed. A worktree in the middle
    -+of a rebase, a `git am` session, a bisect or a cherry-pick or revert
    -+sequence is not clean either, because removing it loses that state. Unclean worktrees or ones with submodules
    -+can be removed with `--force`. The main worktree cannot be removed.
    ++Remove a worktree. The main worktree cannot be removed. Without
    ++`--force`, a worktree is not removed when:
    +++
    ++--
    ++* it has untracked files or modifications in tracked files,
    ++* it has submodules, or
    ++* it is in the middle of a rebase, a `git am` session, a bisect, a
    ++  cherry-pick or a revert, because removing it loses the state of that
    ++  operation.
    ++--
      
      `repair [<path>...]`::
      
    @@ Documentation/git-worktree.adoc: twice. If the destination is already assigned t
      allows the move to proceed; use `--force` twice if the destination is locked.
      +
     -`remove` refuses to remove an unclean worktree unless `--force` is used.
    -+`remove` refuses to remove an unclean worktree, or one in the middle of a
    -+rebase, `git am` session, bisect, or cherry-pick or revert sequence,
    -+unless `--force` is used.
    ++`remove` refuses to remove a worktree in the cases listed under
    ++`remove` above unless `--force` is used.
      To remove a locked worktree, specify `--force` twice.
      
      `-b <new-branch>`::
    @@ builtin/worktree.c: static void check_clean_worktree(struct worktree *wt,
      }
      
     +/*
    -+ * A rebase, "git am", bisect or cherry-pick/revert sequence keeps its
    -+ * state in the worktree's own $GIT_DIR, and removing the worktree
    -+ * throws that away even when "git status" says the files are clean.
    ++ * A rebase, "git am", bisect, cherry-pick or revert keeps its state in
    ++ * the worktree's own $GIT_DIR, and removing the worktree throws that
    ++ * away even when "git status" says the files are clean.
     + */
     +static void check_no_operation_in_progress(struct worktree *wt,
     +					   const char *original_path)
    @@ builtin/worktree.c: static void check_clean_worktree(struct worktree *wt,
     +		die(_("'%s' is in the middle of a bisect, use --force to delete it"),
     +		    original_path);
     +	wt_status_state_free_buffers(&state);
    ++	if (refs_ref_exists(get_worktree_ref_store(wt), "CHERRY_PICK_HEAD"))
    ++		die(_("'%s' is in the middle of a cherry-pick, use --force to delete it"),
    ++		    original_path);
    ++	if (refs_ref_exists(get_worktree_ref_store(wt), "REVERT_HEAD"))
    ++		die(_("'%s' is in the middle of a revert, use --force to delete it"),
    ++		    original_path);
     +	if (is_directory(worktree_git_path(wt, "sequencer")))
     +		die(_("'%s' is in the middle of a cherry-pick or revert, use --force to delete it"),
     +		    original_path);
    @@ t/t2403-worktree-move.sh: test_expect_success 'move worktree with relative path
      	test_cmp expect .git/worktrees/absolute/gitdir
      '
      
    ++test_expect_success 'setup commits that conflict for am, cherry-pick and revert' '
    ++	git worktree add --detach conflict-setup init &&
    ++	(
    ++		cd conflict-setup &&
    ++		test_commit base conflict.t base &&
    ++		git switch --detach init &&
    ++		test_commit side conflict.t side &&
    ++		test_commit side-two
    ++	) &&
    ++	git worktree remove conflict-setup
    ++'
    ++
     +test_expect_success 'remove worktree in the middle of a rebase' '
     +	test_when_finished "rm -rf mid-rebase; git worktree prune" &&
    -+	git worktree add --detach mid-rebase init &&
    -+	test_commit -C mid-rebase rebase-me &&
    ++	git worktree add --detach mid-rebase side &&
     +	test_must_fail git -C mid-rebase rebase -f -x false init &&
     +	test_must_fail git worktree remove mid-rebase 2>err &&
     +	test_grep "in the middle of a rebase" err &&
    @@ t/t2403-worktree-move.sh: test_expect_success 'move worktree with relative path
     +
     +test_expect_success 'remove worktree in the middle of an am session' '
     +	test_when_finished "rm -rf mid-am patch; git worktree prune" &&
    -+	git worktree add --detach mid-am init &&
    -+	test_commit -C mid-am am-me &&
    -+	git -C mid-am format-patch -1 --stdout >patch &&
    -+	git -C mid-am reset --hard init &&
    -+	echo conflict >mid-am/am-me.t &&
    -+	git -C mid-am add am-me.t &&
    -+	git -C mid-am commit -m conflict &&
    -+	test_must_fail git -C mid-am am ../patch &&
    -+	git -C mid-am reset --hard &&
    ++	git format-patch -1 --stdout side >patch &&
    ++	git worktree add --detach mid-am base &&
    ++	(
    ++		cd mid-am &&
    ++		test_must_fail git am ../patch &&
    ++		git reset --hard
    ++	) &&
     +	test_must_fail git worktree remove mid-am 2>err &&
     +	test_grep "in the middle of an am session" err &&
     +	git worktree remove --force mid-am
    @@ t/t2403-worktree-move.sh: test_expect_success 'move worktree with relative path
     +
     +test_expect_success 'remove worktree in the middle of a bisect' '
     +	test_when_finished "rm -rf mid-bisect; git worktree prune" &&
    -+	git worktree add --detach mid-bisect init &&
    -+	test_commit -C mid-bisect bisect-one &&
    -+	test_commit -C mid-bisect bisect-two &&
    -+	git -C mid-bisect bisect start HEAD init &&
    ++	git worktree add --detach mid-bisect side-two &&
    ++	git -C mid-bisect bisect start side-two init &&
     +	test_must_fail git worktree remove mid-bisect 2>err &&
     +	test_grep "in the middle of a bisect" err &&
     +	git worktree remove --force mid-bisect
     +'
     +
    -+test_expect_success 'remove worktree in the middle of a cherry-pick sequence' '
    ++test_expect_success 'remove worktree in the middle of a cherry-pick' '
     +	test_when_finished "rm -rf mid-pick; git worktree prune" &&
    -+	git worktree add --detach mid-pick init &&
    -+	git -C mid-pick switch -c pick-src &&
    -+	test_commit -C mid-pick pick-one &&
    -+	test_commit -C mid-pick pick-two &&
    -+	git -C mid-pick switch --detach init &&
    -+	echo conflict >mid-pick/pick-one.t &&
    -+	git -C mid-pick add pick-one.t &&
    -+	git -C mid-pick commit -m conflict &&
    -+	test_must_fail git -C mid-pick cherry-pick pick-src~1 pick-src &&
    -+	git -C mid-pick checkout --theirs pick-one.t &&
    -+	git -C mid-pick add pick-one.t &&
    -+	git -C mid-pick commit --no-edit &&
    -+	test_path_is_dir .git/worktrees/mid-pick/sequencer &&
    ++	git worktree add --detach mid-pick base &&
    ++	(
    ++		cd mid-pick &&
    ++		test_must_fail git cherry-pick side &&
    ++		git checkout --ours conflict.t &&
    ++		git add conflict.t &&
    ++		git rev-parse --verify CHERRY_PICK_HEAD
    ++	) &&
    ++	test_path_is_missing .git/worktrees/mid-pick/sequencer &&
     +	test_must_fail git worktree remove mid-pick 2>err &&
    -+	test_grep "in the middle of a cherry-pick or revert" err &&
    ++	test_grep "in the middle of a cherry-pick," err &&
     +	git worktree remove --force mid-pick
     +'
    ++
    ++test_expect_success 'remove worktree in the middle of a revert' '
    ++	test_when_finished "rm -rf mid-revert; git worktree prune" &&
    ++	git worktree add --detach mid-revert base &&
    ++	(
    ++		cd mid-revert &&
    ++		test_must_fail git revert side &&
    ++		git checkout --ours conflict.t &&
    ++		git add conflict.t &&
    ++		git rev-parse --verify REVERT_HEAD
    ++	) &&
    ++	test_path_is_missing .git/worktrees/mid-revert/sequencer &&
    ++	test_must_fail git worktree remove mid-revert 2>err &&
    ++	test_grep "in the middle of a revert" err &&
    ++	git worktree remove --force mid-revert
    ++'
    ++
    ++test_expect_success 'remove worktree in the middle of a cherry-pick sequence' '
    ++	test_when_finished "rm -rf mid-pick-seq; git worktree prune" &&
    ++	git worktree add --detach mid-pick-seq base &&
    ++	(
    ++		cd mid-pick-seq &&
    ++		test_must_fail git cherry-pick side side-two &&
    ++		git checkout --theirs conflict.t &&
    ++		git add conflict.t &&
    ++		git commit --no-edit
    ++	) &&
    ++	test_path_is_dir .git/worktrees/mid-pick-seq/sequencer &&
    ++	test_must_fail git worktree remove mid-pick-seq 2>err &&
    ++	test_grep "in the middle of a cherry-pick or revert" err &&
    ++	git worktree remove --force mid-pick-seq
    ++'
     +
      test_done
-:  ---------- > 2:  39eb92d441 doc: for-each-ref: say how to read %(worktreepath) safely
2:  0cd13347e1 ! 3:  990a19fd11 ref-filter: name the worktree of a branch being rebased or bisected
    @@ Commit message
     
         The rest of Git already treats that branch as checked out: "git
         worktree add" and "git branch -d" refuse it, because finishing the
    -    rebase or bisect will check it out again. "git worktree list" shows
    -    such a worktree as "(detached HEAD)", so %(worktreepath) is the only
    -    place a script could find out which worktree is working on the
    -    branch.
    +    rebase or bisect will check it out again. But no command shows which
    +    worktree is working on the branch: "git worktree list" shows such a
    +    worktree as "(detached HEAD)", and %(worktreepath) is empty.
     
    -    Also map the branch that a worktree is rebasing or bisecting to that
    -    worktree, as prepare_checked_out_branches() in branch.c does.
    -    Branches that "rebase --update-refs" will update are not mapped: that
    -    worktree has not checked them out, it only moves them when the rebase
    -    is done.
    +    branch.c already knows the answer, as prepare_checked_out_branches()
    +    records the branch that each worktree has checked out, is rebasing or
    +    is bisecting. Add branch_checked_out_worktree() to look a branch up in
    +    that list, and use it for %(worktreepath) in place of the map that
    +    ref-filter.c builds from the HEAD of each worktree.
     
    -    As a result "git branch" marks such a branch with "+", also when it
    -    runs in the worktree that is rebasing or bisecting it, where it shows
    -    both "* (no branch, rebasing topic)" and "+ topic". Document that.
    +    The new function skips the branches that "rebase --update-refs" will
    +    update. branch_checked_out() includes them, so that they cannot be
    +    checked out or deleted during the rebase, but the worktree that runs
    +    the rebase has not checked them out. %(worktreepath) therefore stays
    +    empty for them, unlike branch_checked_out().
    +
    +    This also changes the result for a bare repository: its HEAD names a
    +    branch, and %(worktreepath) used to give the path of the bare
    +    repository for that branch. "git branch" in a linked worktree marked
    +    the branch with "+", although no worktree has it checked out and "git
    +    worktree add" lets you check it out. prepare_checked_out_branches()
    +    skips bare repositories, so %(worktreepath) is now empty for that
    +    branch and "git branch" no longer marks it.
     
         Reported-by: Kristoffer Haugsbakk <[email protected]>
         Helped-by: Phillip Wood <[email protected]>
    @@ Documentation/git-branch.adoc: DESCRIPTION
      branches are listed; the current branch will be highlighted in green and
      marked with an asterisk.  Any branches checked out in linked worktrees will
     -be highlighted in cyan and marked with a plus sign. Option `-r` causes the
    +-remote-tracking branches to be listed,
     +be highlighted in cyan and marked with a plus sign. A branch that a
    -+worktree is rebasing or bisecting counts as checked out there, so it is
    -+marked in the same way, also in the worktree that is rebasing or
    -+bisecting it. Option `-r` causes the
    - remote-tracking branches to be listed,
    ++worktree is rebasing or bisecting counts as checked out in that
    ++worktree, so the other worktrees mark it in the same way. Option `-r`
    ++causes the remote-tracking branches to be listed,
      and option `-a` shows both local and remote branches.
      
    + If a `<pattern>`
     
      ## Documentation/git-for-each-ref.adoc ##
     @@ Documentation/git-for-each-ref.adoc: but if used together the last option is selected.
    @@ Documentation/git-for-each-ref.adoc: but if used together the last option is sel
     -	out, if it is checked out in any linked worktree. Empty string
     +	out, if it is checked out in any linked worktree. A branch that
     +	a worktree is rebasing or bisecting counts as checked out there,
    -+	although that worktree's `HEAD` is detached. Empty string
    - 	otherwise.
    - 
    - `ahead-behind:<commit-ish>`::
    ++	although that worktree's `HEAD` is detached. A branch that
    ++	`git rebase --update-refs` will update does not. Empty string
    + 	otherwise. If the ref is checked out in more than one worktree,
    + 	only one of them is shown. The path can contain a newline, so
    + 	use one of the quoting options such as `--shell`, or follow
     
    - ## ref-filter.c ##
    -@@ ref-filter.c: static struct expand_data {
    - 
    - struct ref_to_worktree_entry {
    - 	struct hashmap_entry ent;
    --	struct worktree *wt; /* key is wt->head_ref */
    -+	struct worktree *wt;
    -+	char refname[FLEX_ARRAY]; /* the key */
    - };
    - 
    - static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
    -@@ ref-filter.c: static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
    - 	e = container_of(eptr, const struct ref_to_worktree_entry, ent);
    - 	k = container_of(kptr, const struct ref_to_worktree_entry, ent);
    - 
    --	return strcmp(e->wt->head_ref,
    --		keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
    -+	return strcmp(e->refname,
    -+		keydata_aka_refname ? keydata_aka_refname : k->refname);
    + ## branch.c ##
    +@@ branch.c: const char *branch_checked_out(const char *refname)
    + 	return strmap_get(&current_checked_out_branches, refname);
      }
      
    - static struct ref_to_worktree_map {
    ++const char *branch_checked_out_worktree(const char *refname)
    ++{
    ++	const char *path = NULL;
    ++
    ++	prepare_checked_out_branches();
    ++	for (size_t i = 0; i < checked_out_branches_nr; i++) {
    ++		if (checked_out_branches[i].kind != BRANCH_CHECKOUT_KIND_UPDATE_REF &&
    ++		    !strcmp(refname, checked_out_branches[i].refname))
    ++			path = checked_out_branches[i].path;
    ++	}
    ++	return path;
    ++}
    ++
    + const char *branch_bisecting(const char *refname)
    + {
    + 	prepare_checked_out_branches();
    +
    + ## branch.h ##
    +@@ branch.h: void create_branches_recursively(struct repository *r, const char *name,
    +  */
    + const char *branch_checked_out(const char *refname);
    + 
    ++/*
    ++ * If a worktree has the branch 'refname' checked out, or is rebasing or
    ++ * bisecting it, return the path of that worktree, or of the last one if
    ++ * there are more. Otherwise return NULL. Unlike branch_checked_out(),
    ++ * this ignores the branches that "git rebase --update-refs" will
    ++ * update, because no worktree has them checked out.
    ++ */
    ++const char *branch_checked_out_worktree(const char *refname);
    ++
    + /*
    +  * If the branch at 'refname' is currently used for bisecting in a
    +  * worktree, then return the path to that worktree.
    +
    + ## ref-filter.c ##
    +@@
    + #define DISABLE_SIGN_COMPARE_WARNINGS
    + 
    + #include "git-compat-util.h"
    ++#include "branch.h"
    + #include "environment.h"
    + #include "gettext.h"
    + #include "config.h"
    +@@ ref-filter.c: static struct expand_data {
    + 	struct object_info info;
    + } oi, oi_deref;
    + 
    +-struct ref_to_worktree_entry {
    +-	struct hashmap_entry ent;
    +-	struct worktree *wt; /* key is wt->head_ref */
    +-};
    +-
    +-static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
    +-				      const struct hashmap_entry *eptr,
    +-				      const struct hashmap_entry *kptr,
    +-				      const void *keydata_aka_refname)
    +-{
    +-	const struct ref_to_worktree_entry *e, *k;
    +-
    +-	e = container_of(eptr, const struct ref_to_worktree_entry, ent);
    +-	k = container_of(kptr, const struct ref_to_worktree_entry, ent);
    +-
    +-	return strcmp(e->wt->head_ref,
    +-		keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
    +-}
    +-
    +-static struct ref_to_worktree_map {
    +-	struct hashmap map;
    +-	struct worktree **worktrees;
    +-} ref_to_worktree_map;
    +-
    + /*
    +  * The enum atom_type is used as the index of valid_atom array.
    +  * In the atom parsing stage, it will be passed to used_atom.atom_type
     @@ ref-filter.c: static int get_object(struct ref_array_item *ref, int deref,
      	return ret;
      }
      
    -+static void add_worktree_entry(struct hashmap *map, struct worktree *wt,
    -+			       const char *refname)
    -+{
    -+	struct ref_to_worktree_entry *entry;
    -+
    -+	FLEX_ALLOC_STR(entry, refname, refname);
    -+	entry->wt = wt;
    -+	hashmap_entry_init(&entry->ent, strhash(refname));
    -+	hashmap_add(map, &entry->ent);
    -+}
    -+
    -+/*
    -+ * Map each branch to the worktree that has it checked out. A worktree
    -+ * that is rebasing or bisecting a branch has it checked out, too,
    -+ * even though its HEAD may be detached, as for
    -+ * prepare_checked_out_branches() in branch.c.
    -+ */
    - static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
    - {
    +-static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
    +-{
     -	int i;
    -+	struct strbuf ref = STRBUF_INIT;
    - 
    +-
     -	for (i = 0; worktrees[i]; i++) {
     -		if (worktrees[i]->head_ref) {
     -			struct ref_to_worktree_entry *entry;
    @@ ref-filter.c: static int get_object(struct ref_array_item *ref, int deref,
     -			entry->wt = worktrees[i];
     -			hashmap_entry_init(&entry->ent,
     -					strhash(worktrees[i]->head_ref));
    -+	for (size_t i = 0; worktrees[i]; i++) {
    -+		struct worktree *wt = worktrees[i];
    -+		struct wt_status_state state = { 0 };
    - 
    +-
     -			hashmap_add(map, &entry->ent);
    -+		if (wt->is_bare)
    -+			continue;
    -+
    -+		if (wt->head_ref)
    -+			add_worktree_entry(map, wt, wt->head_ref);
    -+
    -+		if (wt_status_check_rebase(wt, &state) &&
    -+		    (state.rebase_in_progress ||
    -+		     state.rebase_interactive_in_progress) &&
    -+		    state.branch) {
    -+			strbuf_reset(&ref);
    -+			strbuf_addf(&ref, "refs/heads/%s", state.branch);
    -+			add_worktree_entry(map, wt, ref.buf);
    - 		}
    -+		wt_status_state_free_buffers(&state);
    -+
    -+		if (wt_status_check_bisect(wt, &state) &&
    -+		    state.bisecting_from) {
    -+			strbuf_reset(&ref);
    -+			strbuf_addf(&ref, "refs/heads/%s", state.bisecting_from);
    -+			add_worktree_entry(map, wt, ref.buf);
    -+		}
    -+		wt_status_state_free_buffers(&state);
    - 	}
    -+	strbuf_release(&ref);
    +-		}
    +-	}
    +-}
    +-
    +-static void lazy_init_worktree_map(void)
    +-{
    +-	if (ref_to_worktree_map.worktrees)
    +-		return;
    +-
    +-	ref_to_worktree_map.worktrees = get_worktrees(the_repository);
    +-	hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
    +-	populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
    +-}
    +-
    + static char *get_worktree_path(const struct ref_array_item *ref)
    + {
    +-	struct hashmap_entry entry, *e;
    +-	struct ref_to_worktree_entry *lookup_result;
    ++	const char *path = branch_checked_out_worktree(ref->refname);
    + 
    +-	lazy_init_worktree_map();
    +-
    +-	hashmap_entry_init(&entry, strhash(ref->refname));
    +-	e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
    +-
    +-	if (!e)
    +-		return xstrdup("");
    +-
    +-	lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
    +-
    +-	return xstrdup(lookup_result->wt->path);
    ++	return xstrdup(path ? path : "");
    + }
    + 
    + /*
    +@@ ref-filter.c: void ref_array_clear(struct ref_array *array)
    + 	FREE_AND_NULL(used_atom);
    + 	used_atom_cnt = 0;
    + 
    +-	if (ref_to_worktree_map.worktrees) {
    +-		hashmap_clear_and_free(&(ref_to_worktree_map.map),
    +-					struct ref_to_worktree_entry, ent);
    +-		free_worktrees(ref_to_worktree_map.worktrees);
    +-		ref_to_worktree_map.worktrees = NULL;
    +-	}
    +-
    + 	FREE_AND_NULL(array->counts);
      }
      
    - static void lazy_init_worktree_map(void)
     
      ## t/t3203-branch-output.sh ##
     @@ t/t3203-branch-output.sh: test_expect_success 'worktree colors correct' '
    @@ t/t3203-branch-output.sh: test_expect_success 'worktree colors correct' '
     +test_expect_success 'branch being rebased in a worktree is marked' '
     +	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
     +	git worktree add -b rebasing rebase_dir branch-two &&
    -+	git -C rebase_dir commit --allow-empty -m rebase-me &&
    -+	test_must_fail git -C rebase_dir rebase -f -x false HEAD~1 &&
    -+	test_must_fail git -C rebase_dir symbolic-ref -q HEAD &&
    ++	(
    ++		cd rebase_dir &&
    ++		git commit --allow-empty -m rebase-me &&
    ++		test_must_fail git rebase -f -x false HEAD~1 &&
    ++		test_must_fail git symbolic-ref -q HEAD
    ++	) &&
     +	git branch --list rebasing >actual &&
     +	echo "+ rebasing" >expect &&
     +	test_cmp expect actual
     +'
     +
    -+test_expect_success 'branch being rebased is marked in its own worktree' '
    -+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
    -+	git worktree add -b rebasing rebase_dir branch-two &&
    -+	git -C rebase_dir commit --allow-empty -m rebase-me &&
    -+	test_must_fail git -C rebase_dir rebase -f -x false HEAD~1 &&
    -+	git -C rebase_dir branch --list rebasing >actual &&
    -+	echo "+ rebasing" >expect &&
    -+	test_cmp expect actual &&
    -+	git -C rebase_dir branch >actual &&
    -+	test_grep "^\* (no branch, rebasing rebasing)" actual
    -+'
    -+
     +test_expect_success 'branch being bisected in a worktree is marked' '
     +	test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
     +	git worktree add -b bisecting bisect_dir branch-two &&
    -+	git -C bisect_dir commit --allow-empty -m bisect-one &&
    -+	git -C bisect_dir commit --allow-empty -m bisect-two &&
    -+	git -C bisect_dir bisect start HEAD HEAD~2 &&
    -+	test_must_fail git -C bisect_dir symbolic-ref -q HEAD &&
    ++	(
    ++		cd bisect_dir &&
    ++		git commit --allow-empty -m bisect-one &&
    ++		git commit --allow-empty -m bisect-two &&
    ++		git bisect start HEAD HEAD~2 &&
    ++		test_must_fail git symbolic-ref -q HEAD
    ++	) &&
     +	git branch --list bisecting >actual &&
     +	echo "+ bisecting" >expect &&
     +	test_cmp expect actual
    @@ t/t6302-for-each-ref-filter.sh: test_expect_success 'validate worktree atom' '
     +	git for-each-ref --format="%(worktreepath)" refs/heads/ >actual &&
     +	test_grep ! detached-rebase actual
     +'
    ++
    ++test_expect_success 'worktree atom ignores the HEAD of a bare repository' '
    ++	test_when_finished "rm -rf bare.git bare-wt" &&
    ++	git clone --bare . bare.git &&
    ++	git -C bare.git symbolic-ref HEAD refs/heads/main &&
    ++	git -C bare.git worktree add --detach ../bare-wt main &&
    ++	git -C bare.git for-each-ref --format="%(worktreepath)" refs/heads/main >actual &&
    ++	echo >expect &&
    ++	test_cmp expect actual &&
    ++	git -C bare-wt branch --list main >actual &&
    ++	echo "  main" >expect &&
    ++	test_cmp expect actual
    ++'
     +
      test_expect_success 'start after with empty value' '
      	cat >expect <<-\EOF &&

-: ---------- > 4: 56e29c448f branch: do not mark the branch the current worktree is rebasing

Signature · 1 line
2.56.0
#25 lore raw

PATCH v4 1/4 worktree remove: refuse a worktree in the middle of an operation

"git worktree remove" refuses to remove a worktree with modified or untracked files unless --force is given, but it removes a worktree that is in the middle of a rebase, a "git am" session, a bisect, a cherry-pick or a revert when its files happen to be clean. The state of that operation lives in the worktree's own $GIT_DIR, so it is lost with the worktree. Examples of such a clean worktree are a rebase stopped at an "edit" or "break" line or after a failed "exec", a cherry-pick sequence after a conflict was resolved and committed, and a single cherry-pick or revert whose conflict was resolved to the current contents, which leaves CHERRY_PICK_HEAD or REVERT_HEAD behind.

Treat such a worktree as unclean: refuse to remove it unless --force is given, and name the operation in the message.

A worktree whose directory is already gone is still removed without --force, as before: the check is part of the check for a clean worktree, which is only done when the directory exists.

---
 Documentation/git-worktree.adoc | 17 ++++--
 builtin/worktree.c              | 37 ++++++++++++-
 t/t2403-worktree-move.sh        | 94 +++++++++++++++++++++++++++++++++
 3 files changed, 142 insertions(+), 6 deletions(-)
Documentation/git-worktree.adoc +12 -5
index e6e77252ab..4a7dc47dd8 100644
@@ -141,10 +141,16 @@ the new working tree location.
 
 `remove`::
 
-Remove a worktree. Only clean worktrees (no untracked files and no
-modification in tracked files) can be removed. Unclean worktrees or ones
-with submodules can be removed with `--force`. The main worktree cannot be
-removed.
+Remove a worktree. The main worktree cannot be removed. Without
+`--force`, a worktree is not removed when:
++
+--
+* it has untracked files or modifications in tracked files,
+* it has submodules, or
+* it is in the middle of a rebase, a `git am` session, a bisect, a
+  cherry-pick or a revert, because removing it loses the state of that
+  operation.
+--
 
 `repair [<path>...]`::
 
@@ -189,7 +195,8 @@ twice. If the destination is already assigned to some other worktree but is
 missing (for instance, if _<new-path>_ was deleted manually), then `--force`
 allows the move to proceed; use `--force` twice if the destination is locked.
 +
-`remove` refuses to remove an unclean worktree unless `--force` is used.
+`remove` refuses to remove a worktree in the cases listed under
+`remove` above unless `--force` is used.
 To remove a locked worktree, specify `--force` twice.
 
 `-b <new-branch>`::
builtin/worktree.c +36 -1
index 77ecd0f71f..7f53215cda 100644
@@ -26,6 +26,7 @@
 #include "submodule.h"
 #include "utf8.h"
 #include "worktree.h"
+#include "wt-status.h"
 #include "quote.h"
 
 #define BUILTIN_WORKTREE_ADD_USAGE \
@@ -1408,6 +1409,38 @@ static void check_clean_worktree(struct worktree *wt,
 			  original_path, ret);
 }
 
+/*
+ * A rebase, "git am", bisect, cherry-pick or revert keeps its state in
+ * the worktree's own $GIT_DIR, and removing the worktree throws that
+ * away even when "git status" says the files are clean.
+ */
+static void check_no_operation_in_progress(struct worktree *wt,
+					   const char *original_path)
+{
+	struct wt_status_state state = { 0 };
+
+	if (wt_status_check_rebase(wt, &state)) {
+		if (state.am_in_progress)
+			die(_("'%s' is in the middle of an am session, use --force to delete it"),
+			    original_path);
+		die(_("'%s' is in the middle of a rebase, use --force to delete it"),
+		    original_path);
+	}
+	if (wt_status_check_bisect(wt, &state))
+		die(_("'%s' is in the middle of a bisect, use --force to delete it"),
+		    original_path);
+	wt_status_state_free_buffers(&state);
+	if (refs_ref_exists(get_worktree_ref_store(wt), "CHERRY_PICK_HEAD"))
+		die(_("'%s' is in the middle of a cherry-pick, use --force to delete it"),
+		    original_path);
+	if (refs_ref_exists(get_worktree_ref_store(wt), "REVERT_HEAD"))
+		die(_("'%s' is in the middle of a revert, use --force to delete it"),
+		    original_path);
+	if (is_directory(worktree_git_path(wt, "sequencer")))
+		die(_("'%s' is in the middle of a cherry-pick or revert, use --force to delete it"),
+		    original_path);
+}
+
 static int delete_git_work_tree(struct worktree *wt)
 {
 	struct strbuf sb = STRBUF_INIT;
@@ -1461,8 +1494,10 @@ static int remove_worktree(int ac, const char **av, const char *prefix,
 	strbuf_release(&errmsg);
 
 	if (file_exists(wt->path)) {
-		if (!force)
+		if (!force) {
+			check_no_operation_in_progress(wt, av[0]);
 			check_clean_worktree(wt, av[0]);
+		}
 
 		ret |= delete_git_work_tree(wt);
 	}
t/t2403-worktree-move.sh +94 -0

98 lines not on this page · raw message

Signature · 1 line
2.56.0
#26 lore raw

Re: [PATCH v4 1/4] worktree remove: refuse a worktree in the middle of an operation

Hi Jasper

Quoted 9 lines · Jasper Mayone
Documentation/git-worktree.adoc +0 -0
index e6e77252ab..4a7dc47dd8 100644
@@ -141,10 +141,16 @@ the new working tree location.
 
  `remove`::
 

Documentation/git-worktree.adoc the new working tree location. · line 149

Quoted 10 lines
Documentation/git-worktree.adoc +6 -4
-Remove a worktree. Only clean worktrees (no untracked files and no
-modification in tracked files) can be removed. Unclean worktrees or ones
-with submodules can be removed with `--force`. The main worktree cannot be
-removed.
+Remove a worktree. The main worktree cannot be removed. Without
+`--force`, a worktree is not removed when:
++
+--
+* it has untracked files or modifications in tracked files,
+* it has submodules, or

This is a list so each item should be a self contained sentence, we should drop the comma above and ", or" here.

Documentation/git-worktree.adoc the new working tree location. · line 152

Quoted 3 lines
Documentation/git-worktree.adoc +3 -0
+* it is in the middle of a rebase, a `git am` session, a bisect, a
+  cherry-pick or a revert, because removing it loses the state of that
+  operation.

Looking at the html rendering of this, it is slightly odd that "git am" is in a different font to the rest of the command names. As we're creating a list we could have a separate item for each command, I'm not sure whether that would be clearer or not.

The rest of this patch looks good

Thanks

Phillip

Quoted 180 lines
Documentation/git-worktree.adoc +3 -1
+--
 
  `repair [<path>...]`::
 
@@ -189,7 +195,8 @@ twice. If the destination is already assigned to some other worktree but is
  missing (for instance, if _<new-path>_ was deleted manually), then `--force`
  allows the move to proceed; use `--force` twice if the destination is locked.
  +
-`remove` refuses to remove an unclean worktree unless `--force` is used.
+`remove` refuses to remove a worktree in the cases listed under
+`remove` above unless `--force` is used.
  To remove a locked worktree, specify `--force` twice.
 
  `-b <new-branch>`::
builtin/worktree.c +36 -1
index 77ecd0f71f..7f53215cda 100644
@@ -26,6 +26,7 @@
  #include "submodule.h"
  #include "utf8.h"
  #include "worktree.h"
+#include "wt-status.h"
  #include "quote.h"
 
  #define BUILTIN_WORKTREE_ADD_USAGE \
@@ -1408,6 +1409,38 @@ static void check_clean_worktree(struct worktree *wt,
  			  original_path, ret);
  }
 
+/*
+ * A rebase, "git am", bisect, cherry-pick or revert keeps its state in
+ * the worktree's own $GIT_DIR, and removing the worktree throws that
+ * away even when "git status" says the files are clean.
+ */
+static void check_no_operation_in_progress(struct worktree *wt,
+					   const char *original_path)
+{
+	struct wt_status_state state = { 0 };
+
+	if (wt_status_check_rebase(wt, &state)) {
+		if (state.am_in_progress)
+			die(_("'%s' is in the middle of an am session, use --force to delete it"),
+			    original_path);
+		die(_("'%s' is in the middle of a rebase, use --force to delete it"),
+		    original_path);
+	}
+	if (wt_status_check_bisect(wt, &state))
+		die(_("'%s' is in the middle of a bisect, use --force to delete it"),
+		    original_path);
+	wt_status_state_free_buffers(&state);
+	if (refs_ref_exists(get_worktree_ref_store(wt), "CHERRY_PICK_HEAD"))
+		die(_("'%s' is in the middle of a cherry-pick, use --force to delete it"),
+		    original_path);
+	if (refs_ref_exists(get_worktree_ref_store(wt), "REVERT_HEAD"))
+		die(_("'%s' is in the middle of a revert, use --force to delete it"),
+		    original_path);
+	if (is_directory(worktree_git_path(wt, "sequencer")))
+		die(_("'%s' is in the middle of a cherry-pick or revert, use --force to delete it"),
+		    original_path);
+}
+
  static int delete_git_work_tree(struct worktree *wt)
  {
  	struct strbuf sb = STRBUF_INIT;
@@ -1461,8 +1494,10 @@ static int remove_worktree(int ac, const char **av, const char *prefix,
  	strbuf_release(&errmsg);
 
  	if (file_exists(wt->path)) {
-		if (!force)
+		if (!force) {
+			check_no_operation_in_progress(wt, av[0]);
  			check_clean_worktree(wt, av[0]);
+		}
 
  		ret |= delete_git_work_tree(wt);
  	}
t/t2403-worktree-move.sh +94 -0
index 69768c1207..2e45cd77f9 100755
@@ -271,4 +271,98 @@ test_expect_success 'move worktree with relative path to absolute path' '
  	test_cmp expect .git/worktrees/absolute/gitdir
  '
 
+test_expect_success 'setup commits that conflict for am, cherry-pick and revert' '
+	git worktree add --detach conflict-setup init &&
+	(
+		cd conflict-setup &&
+		test_commit base conflict.t base &&
+		git switch --detach init &&
+		test_commit side conflict.t side &&
+		test_commit side-two
+	) &&
+	git worktree remove conflict-setup
+'
+
+test_expect_success 'remove worktree in the middle of a rebase' '
+	test_when_finished "rm -rf mid-rebase; git worktree prune" &&
+	git worktree add --detach mid-rebase side &&
+	test_must_fail git -C mid-rebase rebase -f -x false init &&
+	test_must_fail git worktree remove mid-rebase 2>err &&
+	test_grep "in the middle of a rebase" err &&
+	test_path_is_dir mid-rebase &&
+	git worktree remove --force mid-rebase &&
+	test_path_is_missing mid-rebase
+'
+
+test_expect_success 'remove worktree in the middle of an am session' '
+	test_when_finished "rm -rf mid-am patch; git worktree prune" &&
+	git format-patch -1 --stdout side >patch &&
+	git worktree add --detach mid-am base &&
+	(
+		cd mid-am &&
+		test_must_fail git am ../patch &&
+		git reset --hard
+	) &&
+	test_must_fail git worktree remove mid-am 2>err &&
+	test_grep "in the middle of an am session" err &&
+	git worktree remove --force mid-am
+'
+
+test_expect_success 'remove worktree in the middle of a bisect' '
+	test_when_finished "rm -rf mid-bisect; git worktree prune" &&
+	git worktree add --detach mid-bisect side-two &&
+	git -C mid-bisect bisect start side-two init &&
+	test_must_fail git worktree remove mid-bisect 2>err &&
+	test_grep "in the middle of a bisect" err &&
+	git worktree remove --force mid-bisect
+'
+
+test_expect_success 'remove worktree in the middle of a cherry-pick' '
+	test_when_finished "rm -rf mid-pick; git worktree prune" &&
+	git worktree add --detach mid-pick base &&
+	(
+		cd mid-pick &&
+		test_must_fail git cherry-pick side &&
+		git checkout --ours conflict.t &&
+		git add conflict.t &&
+		git rev-parse --verify CHERRY_PICK_HEAD
+	) &&
+	test_path_is_missing .git/worktrees/mid-pick/sequencer &&
+	test_must_fail git worktree remove mid-pick 2>err &&
+	test_grep "in the middle of a cherry-pick," err &&
+	git worktree remove --force mid-pick
+'
+
+test_expect_success 'remove worktree in the middle of a revert' '
+	test_when_finished "rm -rf mid-revert; git worktree prune" &&
+	git worktree add --detach mid-revert base &&
+	(
+		cd mid-revert &&
+		test_must_fail git revert side &&
+		git checkout --ours conflict.t &&
+		git add conflict.t &&
+		git rev-parse --verify REVERT_HEAD
+	) &&
+	test_path_is_missing .git/worktrees/mid-revert/sequencer &&
+	test_must_fail git worktree remove mid-revert 2>err &&
+	test_grep "in the middle of a revert" err &&
+	git worktree remove --force mid-revert
+'
+
+test_expect_success 'remove worktree in the middle of a cherry-pick sequence' '
+	test_when_finished "rm -rf mid-pick-seq; git worktree prune" &&
+	git worktree add --detach mid-pick-seq base &&
+	(
+		cd mid-pick-seq &&
+		test_must_fail git cherry-pick side side-two &&
+		git checkout --theirs conflict.t &&
+		git add conflict.t &&
+		git commit --no-edit
+	) &&
+	test_path_is_dir .git/worktrees/mid-pick-seq/sequencer &&
+	test_must_fail git worktree remove mid-pick-seq 2>err &&
+	test_grep "in the middle of a cherry-pick or revert" err &&
+	git worktree remove --force mid-pick-seq
+'
+
  test_done
#27 lore raw

Re: [PATCH v4 1/4] worktree remove: refuse a worktree in the middle of an operation

Quoted 17 lines · Phillip Wood

Hi Jasper

Quoted 11 lines · Jasper Mayone
Documentation/git-worktree.adoc +0 -3
index e6e77252ab..4a7dc47dd8 100644
@@ -141,10 +141,16 @@ the new working tree location.
   `remove`::
 -Remove a worktree. Only clean worktrees (no untracked files and no
-modification in tracked files) can be removed. Unclean worktrees or ones
-with submodules can be removed with `--force`. The main worktree cannot be
-removed.
Quoted 12 lines

Documentation/git-worktree.adoc the new working tree location. · line 149

Quoted 6 lines
Documentation/git-worktree.adoc +6 -0
+Remove a worktree. The main worktree cannot be removed. Without
+`--force`, a worktree is not removed when:
++
+--
+* it has untracked files or modifications in tracked files,
+* it has submodules, or

This is a list so each item should be a self contained sentence, we should drop the comma above and ", or" here.

Quoted 3 lines
Documentation/git-worktree.adoc +3 -0
+* it is in the middle of a rebase, a `git am` session, a bisect, a
+  cherry-pick or a revert, because removing it loses the state of that
+  operation.

Well, each item is a clause/phrase… I actually think the “or” fits better than rewriting the list introduction and items to be complete sentences.

I think that construction is ok as-is.

#28 lore raw

PATCH v4 2/4 doc: for-each-ref: say how to read %(worktreepath) safely

In reply to Jasper Mayone

The path that %(worktreepath) gives can contain a newline, which breaks a script that reads one record per line. Say how to avoid
that: use a quoting option, or end the atom with %00 and look for the NUL before the LF that ends the record.

Also say that only one worktree is shown when a branch is checked out in more than one worktree.

---
 Documentation/git-for-each-ref.adoc | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
Documentation/git-for-each-ref.adoc +6 -1
index a7b31e8aaf..9247737aa7 100644
@@ -183,7 +183,12 @@ but if used together the last option is selected.
 `worktreepath`::
 	The absolute path to the worktree in which the ref is checked
 	out, if it is checked out in any linked worktree. Empty string
-	otherwise.
+	otherwise. If the ref is checked out in more than one worktree,
+	only one of them is shown. The path can contain a newline, so
+	use one of the quoting options such as `--shell`, or follow
+	`%(worktreepath)` with `%00` and parse the output by looking for
+	the `NUL` after the path and then for the `LF` that ends each
+	record.
 
 `ahead-behind:<commit-ish>`::
 	Two integers, separated by a space, demonstrating the number of
Signature · 1 line
2.56.0
#29 lore raw

Re: [PATCH v4 2/4] doc: for-each-ref: say how to read %(worktreepath) safely

Quoted 8 lines · Jasper Mayone

The path that %(worktreepath) gives can contain a newline, which breaks a script that reads one record per line. Say how to avoid
that: use a quoting option, or end the atom with %00 and look for the NUL before the LF that ends the record.

Also say that only one worktree is shown when a branch is checked out in more than one worktree.

I was under the impression a branch could not be checked out in multiple worktrees due to possible races from each worktree performing updates; or at least, that the porcelain would refuse to create such worktrees.

Has that limitation been lifted recently?

Quoted 27 lines
---
 Documentation/git-for-each-ref.adoc | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
Documentation/git-for-each-ref.adoc +6 -2
index a7b31e8aaf..9247737aa7 100644
@@ -183,7 +183,12 @@ but if used together the last option is selected.
 `worktreepath`::
        The absolute path to the worktree in which the ref is checked
        out, if it is checked out in any linked worktree. Empty string
-       otherwise.
+       otherwise. If the ref is checked out in more than one worktree,
+       only one of them is shown. The path can contain a newline, so
+       use one of the quoting options such as `--shell`, or follow
+       `%(worktreepath)` with `%00` and parse the output by looking for
+       the `NUL` after the path and then for the `LF` that ends each
+       record.
 
 `ahead-behind:<commit-ish>`::
        Two integers, separated by a space, demonstrating the number of
--

2.56.0

Signature · 1 line
D. Ben Knoble
#30 lore raw

Re: [PATCH v4 2/4] doc: for-each-ref: say how to read %(worktreepath) safely

Hi Ben

Quoted 10 lines · D. Ben Knoble
Quoted 8 lines · Jasper Mayone

The path that %(worktreepath) gives can contain a newline, which breaks a script that reads one record per line. Say how to avoid
that: use a quoting option, or end the atom with %00 and look for the NUL before the LF that ends the record.

Also say that only one worktree is shown when a branch is checked out in more than one worktree.

Quoted 6 lines

I was under the impression a branch could not be checked out in multiple worktrees due to possible races from each worktree performing updates; or at least, that the porcelain would refuse to create such worktrees.

Has that limitation been lifted recently?

No, it is not encouraged, but it is possible to checkout the same branch in more than one worktree with "git worktree add --force", or "git checkout --ignore-other-worktrees". Those options have existed for some time. It's also possible to bypass the checks by using "git symbolic-ref".

Thanks

Phillip

Quoted 29 lines
Quoted 27 lines
---
  Documentation/git-for-each-ref.adoc | 7 ++++++-
  1 file changed, 6 insertions(+), 1 deletion(-)
Documentation/git-for-each-ref.adoc +6 -2
index a7b31e8aaf..9247737aa7 100644
@@ -183,7 +183,12 @@ but if used together the last option is selected.
  `worktreepath`::
         The absolute path to the worktree in which the ref is checked
         out, if it is checked out in any linked worktree. Empty string
-       otherwise.
+       otherwise. If the ref is checked out in more than one worktree,
+       only one of them is shown. The path can contain a newline, so
+       use one of the quoting options such as `--shell`, or follow
+       `%(worktreepath)` with `%00` and parse the output by looking for
+       the `NUL` after the path and then for the `LF` that ends each
+       record.
 
  `ahead-behind:<commit-ish>`::
         Two integers, separated by a space, demonstrating the number of
--

2.56.0

#31 lore raw

Re: [PATCH v4 2/4] doc: for-each-ref: say how to read %(worktreepath) safely

Quoted 21 lines · Phillip Wood

Hi Ben

Quoted 8 lines · D. Ben Knoble
Quoted 7 lines · Jasper Mayone

The path that %(worktreepath) gives can contain a newline, which breaks a script that reads one record per line. Say how to avoid
that: use a quoting option, or end the atom with %00 and look for the NUL before the LF that ends the record.

Quoted 7 lines
Quoted 2 lines

Also say that only one worktree is shown when a branch is checked out in more than one worktree.

I was under the impression a branch could not be checked out in multiple worktrees due to possible races from each worktree performing updates; or at least, that the porcelain would refuse to create such worktrees.
Has that limitation been lifted recently?

Quoted 6 lines

No, it is not encouraged, but it is possible to checkout the same branch in more than one worktree with "git worktree add --force", or "git checkout --ignore-other-worktrees". Those options have existed for some time. It's also possible to bypass the checks by using "git symbolic-ref".

Thanks

Phillip

Faulty memory, then, thanks.

#32 lore raw

Re: [PATCH v4 2/4] doc: for-each-ref: say how to read %(worktreepath) safely

Quoted 4 lines · Ben Knoble
Quoted 4 lines
Quoted 4 lines

I was under the impression a branch could not be checked out in multiple worktrees due to possible races from each worktree performing updates; or at least, that the porcelain would refuse to create such worktrees.

Phillip's answer covers everything, but I am not sure if "possible races" is a good explanation to describe the reason this is strongly discouraged.

You checkout 'main' in worktree A and worktree B, so their working tree files and their index files all match what is recorded at the commit pointed at by 'main'.

You then make changes and commit your changes in worktree A. The 'main' branch now points at a newly created commit, and the working tree files and the index in worktree A are in sync with the new commit (note: unlike the initial state, I am not saying "all match" in this case, as this commit may have been a partial one. The important thing is that from the end-user's perspective who has been working in worktree A, things are consistent without any unexpected change).

In the meantime, if worktree B weren't doing anything, its index and the working tree files have not changed since the beginning. Yet because 'main' (hence HEAD) moved, "git status" in worktree B reports as if it reverted the change made in the updated 'main'.

That would be a grave confusion, and that is what we want to avoid by forbidding a single branch from being checked out in multiple worktrees. But given that worktree B was doing absolutely nothing while worktree A was doing its own thing, I would not call this a "race". It is something else.

Thanks.

#33 lore raw

Re: [PATCH v4 2/4] doc: for-each-ref: say how to read %(worktreepath) safely

In reply to Jasper Mayone

Hi Jasper

Thanks for adding this, it looks good

Phillip

Quoted 32 lines · Jasper Mayone

The path that %(worktreepath) gives can contain a newline, which breaks a script that reads one record per line. Say how to avoid
that: use a quoting option, or end the atom with %00 and look for the NUL before the LF that ends the record.

Also say that only one worktree is shown when a branch is checked out in more than one worktree.

---
  Documentation/git-for-each-ref.adoc | 7 ++++++-
  1 file changed, 6 insertions(+), 1 deletion(-)
Documentation/git-for-each-ref.adoc +6 -1
index a7b31e8aaf..9247737aa7 100644
@@ -183,7 +183,12 @@ but if used together the last option is selected.
  `worktreepath`::
  	The absolute path to the worktree in which the ref is checked
  	out, if it is checked out in any linked worktree. Empty string
-	otherwise.
+	otherwise. If the ref is checked out in more than one worktree,
+	only one of them is shown. The path can contain a newline, so
+	use one of the quoting options such as `--shell`, or follow
+	`%(worktreepath)` with `%00` and parse the output by looking for
+	the `NUL` after the path and then for the `LF` that ends each
+	record.
 
  `ahead-behind:<commit-ish>`::
  	Two integers, separated by a space, demonstrating the number of
#34 lore raw

PATCH v4 3/4 ref-filter: name the worktree of a branch being rebased or bisected

In reply to Jasper Mayone

%(worktreepath) gives the worktree that has a branch checked out, and "git branch" uses it to mark such branches with "+". It only looks at the HEAD of each worktree, so while a worktree is rebasing or bisecting a branch, its HEAD is detached and the branch shows no worktree at all.

The rest of Git already treats that branch as checked out: "git worktree add" and "git branch -d" refuse it, because finishing the rebase or bisect will check it out again. But no command shows which worktree is working on the branch: "git worktree list" shows such a worktree as "(detached HEAD)", and %(worktreepath) is empty.

branch.c already knows the answer, as prepare_checked_out_branches() records the branch that each worktree has checked out, is rebasing or is bisecting. Add branch_checked_out_worktree() to look a branch up in that list, and use it for %(worktreepath) in place of the map that ref-filter.c builds from the HEAD of each worktree.

The new function skips the branches that "rebase --update-refs" will update. branch_checked_out() includes them, so that they cannot be checked out or deleted during the rebase, but the worktree that runs the rebase has not checked them out. %(worktreepath) therefore stays empty for them, unlike branch_checked_out().

This also changes the result for a bare repository: its HEAD names a branch, and %(worktreepath) used to give the path of the bare repository for that branch. "git branch" in a linked worktree marked the branch with "+", although no worktree has it checked out and "git worktree add" lets you check it out. prepare_checked_out_branches() skips bare repositories, so %(worktreepath) is now empty for that branch and "git branch" no longer marks it.

---
 Documentation/git-branch.adoc       |  6 ++-
 Documentation/git-for-each-ref.adoc |  5 +-
 branch.c                            | 13 +++++
 branch.h                            |  9 ++++
 ref-filter.c                        | 74 ++--------------------------
 t/t3203-branch-output.sh            | 29 +++++++++++
 t/t6302-for-each-ref-filter.sh      | 76 +++++++++++++++++++++++++++++
 7 files changed, 138 insertions(+), 74 deletions(-)
Documentation/git-branch.adoc +4 -2
index bfdf459329..510b0afc74 100644
@@ -33,8 +33,10 @@ DESCRIPTION
 If `--list` is given, or if there are no non-option arguments, existing
 branches are listed; the current branch will be highlighted in green and
 marked with an asterisk.  Any branches checked out in linked worktrees will
-be highlighted in cyan and marked with a plus sign. Option `-r` causes the
-remote-tracking branches to be listed,
+be highlighted in cyan and marked with a plus sign. A branch that a
+worktree is rebasing or bisecting counts as checked out in that
+worktree, so the other worktrees mark it in the same way. Option `-r`
+causes the remote-tracking branches to be listed,
 and option `-a` shows both local and remote branches.
 
 If a `<pattern>`
Documentation/git-for-each-ref.adoc +4 -1
index 9247737aa7..4456b4809a 100644
@@ -182,7 +182,10 @@ but if used together the last option is selected.
 
 `worktreepath`::
 	The absolute path to the worktree in which the ref is checked
-	out, if it is checked out in any linked worktree. Empty string
+	out, if it is checked out in any linked worktree. A branch that
+	a worktree is rebasing or bisecting counts as checked out there,
+	although that worktree's `HEAD` is detached. A branch that
+	`git rebase --update-refs` will update does not. Empty string
 	otherwise. If the ref is checked out in more than one worktree,
 	only one of them is shown. The path can contain a newline, so
 	use one of the quoting options such as `--shell`, or follow
branch.c +13 -0
index 5bb1c28915..8dab72d857 100644
@@ -485,6 +485,19 @@ const char *branch_checked_out(const char *refname)
 	return strmap_get(&current_checked_out_branches, refname);
 }
 
+const char *branch_checked_out_worktree(const char *refname)
+{
+	const char *path = NULL;
+
+	prepare_checked_out_branches();
+	for (size_t i = 0; i < checked_out_branches_nr; i++) {
+		if (checked_out_branches[i].kind != BRANCH_CHECKOUT_KIND_UPDATE_REF &&
+		    !strcmp(refname, checked_out_branches[i].refname))
+			path = checked_out_branches[i].path;
+	}
+	return path;
+}
+
 const char *branch_bisecting(const char *refname)
 {
 	prepare_checked_out_branches();
branch.h +9 -0
index 95b2431f24..60cb92a3e4 100644
@@ -106,6 +106,15 @@ void create_branches_recursively(struct repository *r, const char *name,
  */
 const char *branch_checked_out(const char *refname);
 
+/*
+ * If a worktree has the branch 'refname' checked out, or is rebasing or
+ * bisecting it, return the path of that worktree, or of the last one if
+ * there are more. Otherwise return NULL. Unlike branch_checked_out(),
+ * this ignores the branches that "git rebase --update-refs" will
+ * update, because no worktree has them checked out.
+ */
+const char *branch_checked_out_worktree(const char *refname);
+
 /*
  * If the branch at 'refname' is currently used for bisecting in a
  * worktree, then return the path to that worktree.
ref-filter.c +3 -71

101 lines not on this page · raw message

t/t3203-branch-output.sh +29 -0
index 7c44186341..debfac5f26 100755
@@ -442,6 +442,35 @@ test_expect_success 'worktree colors correct' '
 	test_cmp expect actual
 '
 
+test_expect_success 'branch being rebased in a worktree is marked' '
+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebase_dir branch-two &&
+	(
+		cd rebase_dir &&
+		git commit --allow-empty -m rebase-me &&
+		test_must_fail git rebase -f -x false HEAD~1 &&
+		test_must_fail git symbolic-ref -q HEAD
+	) &&
+	git branch --list rebasing >actual &&
+	echo "+ rebasing" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success 'branch being bisected in a worktree is marked' '
+	test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
+	git worktree add -b bisecting bisect_dir branch-two &&
+	(
+		cd bisect_dir &&
+		git commit --allow-empty -m bisect-one &&
+		git commit --allow-empty -m bisect-two &&
+		git bisect start HEAD HEAD~2 &&
+		test_must_fail git symbolic-ref -q HEAD
+	) &&
+	git branch --list bisecting >actual &&
+	echo "+ bisecting" >expect &&
+	test_cmp expect actual
+'
+
 test_expect_success "set up color tests" '
 	echo "<RED>main<RESET>" >expect.color &&
 	echo "main" >expect.bare &&
t/t6302-for-each-ref-filter.sh +76 -0

88 lines not on this page · raw message

Signature · 1 line
2.56.0
#35 lore raw

Re: [PATCH v4 3/4] ref-filter: name the worktree of a branch being rebased or bisected

Hi Jasper

Quoted 24 lines · Jasper Mayone

%(worktreepath) gives the worktree that has a branch checked out, and "git branch" uses it to mark such branches with "+". It only looks at the HEAD of each worktree, so while a worktree is rebasing or bisecting a branch, its HEAD is detached and the branch shows no worktree at all.

The rest of Git already treats that branch as checked out: "git worktree add" and "git branch -d" refuse it, because finishing the rebase or bisect will check it out again. But no command shows which worktree is working on the branch: "git worktree list" shows such a worktree as "(detached HEAD)", and %(worktreepath) is empty.

branch.c already knows the answer, as prepare_checked_out_branches() records the branch that each worktree has checked out, is rebasing or is bisecting. Add branch_checked_out_worktree() to look a branch up in that list, and use it for %(worktreepath) in place of the map that ref-filter.c builds from the HEAD of each worktree.

The new function skips the branches that "rebase --update-refs" will update. branch_checked_out() includes them, so that they cannot be checked out or deleted during the rebase, but the worktree that runs the rebase has not checked them out. %(worktreepath) therefore stays empty for them, unlike branch_checked_out().

Quoted 7 lines

This also changes the result for a bare repository: its HEAD names a branch, and %(worktreepath) used to give the path of the bare repository for that branch. "git branch" in a linked worktree marked the branch with "+", although no worktree has it checked out and "git worktree add" lets you check it out. prepare_checked_out_branches() skips bare repositories, so %(worktreepath) is now empty for that branch and "git branch" no longer marks it.

We now document the change in behavior - good.

Quoted 8 lines
branch.c +0 -0
index 5bb1c28915..8dab72d857 100644
@@ -485,6 +485,19 @@ const char *branch_checked_out(const char *refname)
  	return strmap_get(&current_checked_out_branches, refname);
  }
 

branch.c const char *branch_checked_out(const char *refname) · line 497

Quoted 10 lines
branch.c +10 -0
+const char *branch_checked_out_worktree(const char *refname)
+{
+	const char *path = NULL;
+
+	prepare_checked_out_branches();
+	for (size_t i = 0; i < checked_out_branches_nr; i++) {
+		if (checked_out_branches[i].kind != BRANCH_CHECKOUT_KIND_UPDATE_REF &&
+		    !strcmp(refname, checked_out_branches[i].refname))
+			path = checked_out_branches[i].path;
+	}

Iterating over all the worktrees for every ref is going to be slower than it needs to be. As I said in [1] we should use a hash map to map branch names to the worktree where they are checked out. That is also what the existing ref-filter code does.

Then we can add a function to get the worktree path where a branch is checked out and call that from the ref-filter code.

Thanks

Phillip

Quoted 269 lines
branch.c +3 -0
+	return path;
+}
+
  const char *branch_bisecting(const char *refname)
  {
  	prepare_checked_out_branches();
branch.h +9 -0
index 95b2431f24..60cb92a3e4 100644
@@ -106,6 +106,15 @@ void create_branches_recursively(struct repository *r, const char *name,
   */
  const char *branch_checked_out(const char *refname);
 
+/*
+ * If a worktree has the branch 'refname' checked out, or is rebasing or
+ * bisecting it, return the path of that worktree, or of the last one if
+ * there are more. Otherwise return NULL. Unlike branch_checked_out(),
+ * this ignores the branches that "git rebase --update-refs" will
+ * update, because no worktree has them checked out.
+ */
+const char *branch_checked_out_worktree(const char *refname);
+
  /*
   * If the branch at 'refname' is currently used for bisecting in a
   * worktree, then return the path to that worktree.
ref-filter.c +3 -71
index bdf54f6f59..b636e56199 100644
@@ -2,6 +2,7 @@
  #define DISABLE_SIGN_COMPARE_WARNINGS
 
  #include "git-compat-util.h"
+#include "branch.h"
  #include "environment.h"
  #include "gettext.h"
  #include "config.h"
@@ -95,30 +96,6 @@ static struct expand_data {
  	struct object_info info;
  } oi, oi_deref;
 
-struct ref_to_worktree_entry {
-	struct hashmap_entry ent;
-	struct worktree *wt; /* key is wt->head_ref */
-};
-
-static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
-				      const struct hashmap_entry *eptr,
-				      const struct hashmap_entry *kptr,
-				      const void *keydata_aka_refname)
-{
-	const struct ref_to_worktree_entry *e, *k;
-
-	e = container_of(eptr, const struct ref_to_worktree_entry, ent);
-	k = container_of(kptr, const struct ref_to_worktree_entry, ent);
-
-	return strcmp(e->wt->head_ref,
-		keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
-}
-
-static struct ref_to_worktree_map {
-	struct hashmap map;
-	struct worktree **worktrees;
-} ref_to_worktree_map;
-
  /*
   * The enum atom_type is used as the index of valid_atom array.
   * In the atom parsing stage, it will be passed to used_atom.atom_type
@@ -2380,49 +2357,11 @@ static int get_object(struct ref_array_item *ref, int deref,
  	return ret;
  }
 
-static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
-{
-	int i;
-
-	for (i = 0; worktrees[i]; i++) {
-		if (worktrees[i]->head_ref) {
-			struct ref_to_worktree_entry *entry;
-			entry = xmalloc(sizeof(*entry));
-			entry->wt = worktrees[i];
-			hashmap_entry_init(&entry->ent,
-					strhash(worktrees[i]->head_ref));
-
-			hashmap_add(map, &entry->ent);
-		}
-	}
-}
-
-static void lazy_init_worktree_map(void)
-{
-	if (ref_to_worktree_map.worktrees)
-		return;
-
-	ref_to_worktree_map.worktrees = get_worktrees(the_repository);
-	hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
-	populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
-}
-
  static char *get_worktree_path(const struct ref_array_item *ref)
  {
-	struct hashmap_entry entry, *e;
-	struct ref_to_worktree_entry *lookup_result;
+	const char *path = branch_checked_out_worktree(ref->refname);
 
-	lazy_init_worktree_map();
-
-	hashmap_entry_init(&entry, strhash(ref->refname));
-	e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
-
-	if (!e)
-		return xstrdup("");
-
-	lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
-
-	return xstrdup(lookup_result->wt->path);
+	return xstrdup(path ? path : "");
  }
 
  /*
@@ -3195,13 +3134,6 @@ void ref_array_clear(struct ref_array *array)
  	FREE_AND_NULL(used_atom);
  	used_atom_cnt = 0;
 
-	if (ref_to_worktree_map.worktrees) {
-		hashmap_clear_and_free(&(ref_to_worktree_map.map),
-					struct ref_to_worktree_entry, ent);
-		free_worktrees(ref_to_worktree_map.worktrees);
-		ref_to_worktree_map.worktrees = NULL;
-	}
-
  	FREE_AND_NULL(array->counts);
  }
 
t/t3203-branch-output.sh +29 -0
index 7c44186341..debfac5f26 100755
@@ -442,6 +442,35 @@ test_expect_success 'worktree colors correct' '
  	test_cmp expect actual
  '
 
+test_expect_success 'branch being rebased in a worktree is marked' '
+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebase_dir branch-two &&
+	(
+		cd rebase_dir &&
+		git commit --allow-empty -m rebase-me &&
+		test_must_fail git rebase -f -x false HEAD~1 &&
+		test_must_fail git symbolic-ref -q HEAD
+	) &&
+	git branch --list rebasing >actual &&
+	echo "+ rebasing" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success 'branch being bisected in a worktree is marked' '
+	test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
+	git worktree add -b bisecting bisect_dir branch-two &&
+	(
+		cd bisect_dir &&
+		git commit --allow-empty -m bisect-one &&
+		git commit --allow-empty -m bisect-two &&
+		git bisect start HEAD HEAD~2 &&
+		test_must_fail git symbolic-ref -q HEAD
+	) &&
+	git branch --list bisecting >actual &&
+	echo "+ bisecting" >expect &&
+	test_cmp expect actual
+'
+
  test_expect_success "set up color tests" '
  	echo "<RED>main<RESET>" >expect.color &&
  	echo "main" >expect.bare &&
t/t6302-for-each-ref-filter.sh +76 -0
index 7f060d97bf..317ed6f6cd 100755
@@ -3,6 +3,7 @@
  test_description='test for-each-refs usage of ref-filter APIs'
 
  . ./test-lib.sh
+. "$TEST_DIRECTORY"/lib-rebase.sh
  . "$TEST_DIRECTORY"/lib-gpg.sh
 
  test_expect_success 'setup some history and refs' '
@@ -541,6 +542,81 @@ test_expect_success 'validate worktree atom' '
  	test_cmp expect actual
  '
 
+test_expect_success 'worktree atom names a worktree rebasing the branch' '
+	test_when_finished "git -C rebasing rebase --abort; rm -rf rebasing; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebasing main &&
+	git -C rebasing commit --allow-empty -m rebase-me &&
+	test_must_fail git -C rebasing rebase -f -x false main &&
+	test_must_fail git -C rebasing symbolic-ref -q HEAD &&
+	echo "$(pwd)/rebasing" >expect &&
+	git for-each-ref --format="%(worktreepath)" refs/heads/rebasing >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'worktree atom names a worktree bisecting the branch' '
+	test_when_finished "git -C bisecting bisect reset; rm -rf bisecting; git worktree prune; git branch -D bisecting" &&
+	git worktree add -b bisecting bisecting main &&
+	git -C bisecting commit --allow-empty -m bisect-one &&
+	git -C bisecting commit --allow-empty -m bisect-two &&
+	git -C bisecting bisect start HEAD main &&
+	test_must_fail git -C bisecting symbolic-ref -q HEAD &&
+	echo "$(pwd)/bisecting" >expect &&
+	git for-each-ref --format="%(worktreepath)" refs/heads/bisecting >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'worktree atom with an interactive rebase stopped at edit' '
+	test_when_finished "git -C editing rebase --abort; rm -rf editing; git worktree prune; git branch -D editing" &&
+	git worktree add -b editing editing main &&
+	git -C editing commit --allow-empty -m edit-me &&
+	(
+		set_fake_editor &&
+		FAKE_LINES="edit 1" git -C editing rebase -i --keep-empty HEAD~1
+	) &&
+	test_must_fail git -C editing symbolic-ref -q HEAD &&
+	echo "$(pwd)/editing" >expect &&
+	git for-each-ref --format="%(worktreepath)" refs/heads/editing >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'worktree atom ignores branches rebase --update-refs will move' '
+	test_when_finished "git -C updating rebase --abort; rm -rf updating; git worktree prune; git branch -D updating mid" &&
+	git worktree add -b updating updating main &&
+	git -C updating commit --allow-empty -m one &&
+	git -C updating branch mid &&
+	git -C updating commit --allow-empty -m two &&
+	test_must_fail git -C updating rebase -f --update-refs -x false main &&
+	git for-each-ref --format="%(refname:short) [%(worktreepath)]" \
+		refs/heads/updating refs/heads/mid >actual &&
+	cat >expect <<-EOF &&
+	mid []
+	updating [$(pwd)/updating]
+	EOF
+	test_cmp expect actual
+'
+
+test_expect_success 'worktree atom ignores a rebase of a detached HEAD' '
+	test_when_finished "git -C detached-rebase rebase --abort; rm -rf detached-rebase; git worktree prune" &&
+	git worktree add --detach detached-rebase main &&
+	git -C detached-rebase commit --allow-empty -m detached &&
+	test_must_fail git -C detached-rebase rebase -f -x false main &&
+	git for-each-ref --format="%(worktreepath)" refs/heads/ >actual &&
+	test_grep ! detached-rebase actual
+'
+
+test_expect_success 'worktree atom ignores the HEAD of a bare repository' '
+	test_when_finished "rm -rf bare.git bare-wt" &&
+	git clone --bare . bare.git &&
+	git -C bare.git symbolic-ref HEAD refs/heads/main &&
+	git -C bare.git worktree add --detach ../bare-wt main &&
+	git -C bare.git for-each-ref --format="%(worktreepath)" refs/heads/main >actual &&
+	echo >expect &&
+	test_cmp expect actual &&
+	git -C bare-wt branch --list main >actual &&
+	echo "  main" >expect &&
+	test_cmp expect actual
+'
+
  test_expect_success 'start after with empty value' '
  	cat >expect <<-\EOF &&
  	refs/heads/main
#36 lore raw

PATCH v4 4/4 branch: do not mark the branch the current worktree is rebasing

In reply to Jasper Mayone

Since the previous commit, "git branch" marks a branch with "+" when a worktree is rebasing or bisecting it. In that worktree itself, the list already starts with "* (no branch, rebasing topic)", so the "+ topic" line below it says the same thing twice.

The default format cannot tell that apart: %(worktreepath) gives the same path either way, and comparing it with %(if:equals=...) is not safe because a path, or a branch name, can contain the ")" that ends the atom. So build a second format that has no "+" marker and no "(path)" for -vv, and use it for each branch that branch_checked_out_worktree() maps to the current worktree. A branch that is checked out normally in the current worktree also gets that format, but %(HEAD) still marks it with "*" and -vv already hides its path, so its output does not change.

To pick a format for each branch, print_ref_list() now formats the branches itself in place of print_formatted_ref_array(), keeping --omit-empty. A format given with --format is used for every branch, as before.

---
 builtin/branch.c         | 103 ++++++++++++++++++++++++++++++---------
 t/t3203-branch-output.sh |  22 ++++++++-
 2 files changed, 101 insertions(+), 24 deletions(-)
builtin/branch.c +80 -23
index a613148fc7..b55a400217 100644
@@ -418,16 +418,28 @@ static const char *quote_literal_for_format(const char *s)
 	return buf.buf;
 }
 
-static char *build_format(struct ref_filter *filter, int maxwidth, const char *remote_prefix)
+/*
+ * With "show_worktree" unset, the format does not mark a branch that is
+ * checked out in a worktree, nor show the path of that worktree. It is
+ * used for a branch that the current worktree is rebasing or bisecting,
+ * because the "(no branch, ...)" line already names it.
+ */
+static char *build_format(struct ref_filter *filter, int maxwidth,
+			  const char *remote_prefix, int show_worktree)
 {
 	struct strbuf fmt = STRBUF_INIT;
 	struct strbuf local = STRBUF_INIT;
 	struct strbuf remote = STRBUF_INIT;
 
-	strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else)  %s%%(end)%%(end)",
-			branch_get_color(BRANCH_COLOR_CURRENT),
-			branch_get_color(BRANCH_COLOR_WORKTREE),
-			branch_get_color(BRANCH_COLOR_LOCAL));
+	if (show_worktree)
+		strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else)  %s%%(end)%%(end)",
+			    branch_get_color(BRANCH_COLOR_CURRENT),
+			    branch_get_color(BRANCH_COLOR_WORKTREE),
+			    branch_get_color(BRANCH_COLOR_LOCAL));
+	else
+		strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)  %s%%(end)",
+			    branch_get_color(BRANCH_COLOR_CURRENT),
+			    branch_get_color(BRANCH_COLOR_LOCAL));
 	strbuf_addf(&remote, "  %s",
 		    branch_get_color(BRANCH_COLOR_REMOTE));
 
@@ -447,8 +459,9 @@ static char *build_format(struct ref_filter *filter, int maxwidth, const char *r
 
 		if (filter->verbose > 1)
 		{
-			strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)",
-				    branch_get_color(BRANCH_COLOR_WORKTREE), branch_get_color(BRANCH_COLOR_RESET));
+			if (show_worktree)
+				strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)",
+					    branch_get_color(BRANCH_COLOR_WORKTREE), branch_get_color(BRANCH_COLOR_RESET));
 			strbuf_addf(&local, "%%(if)%%(upstream)%%(then)[%s%%(upstream:short)%s%%(if)%%(upstream:track)"
 				    "%%(then): %%(upstream:track,nobracket)%%(end)] %%(end)%%(contents:subject)",
 				    branch_get_color(BRANCH_COLOR_UPSTREAM), branch_get_color(BRANCH_COLOR_RESET));
@@ -477,6 +490,32 @@ static char *build_format(struct ref_filter *filter, int maxwidth, const char *r
 	return strbuf_detach(&fmt, NULL);
 }
 
+static char *current_worktree_path(void)
+{
+	struct worktree **worktrees = get_worktrees(the_repository);
+	char *path = NULL;
+
+	for (size_t i = 0; worktrees[i]; i++) {
+		if (worktrees[i]->is_current) {
+			path = xstrdup(worktrees[i]->path);
+			break;
+		}
+	}
+	free_worktrees(worktrees);
+	return path;
+}
+
+/*
+ * Is "refname" checked out in the worktree at "here", or is that
+ * worktree rebasing or bisecting it?
+ */
+static int checked_out_here(const char *refname, const char *here)
+{
+	const char *path = branch_checked_out_worktree(refname);
+
+	return path && !strcmp(path, here);
+}
+
 static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sorting,
 			   struct ref_format *format, struct string_list *output)
 {
@@ -485,6 +524,9 @@ static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sortin
 	int maxwidth = 0;
 	const char *remote_prefix = "";
 	char *to_free = NULL;
+	struct ref_format here_format = REF_FORMAT_INIT;
+	char *here_to_free = NULL, *here = NULL;
+	struct strbuf out = STRBUF_INIT, err = STRBUF_INIT;
 
 	/*
 	 * If we are listing more than just remote branches,
@@ -501,39 +543,54 @@ static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sortin
 	if (filter->verbose)
 		maxwidth = calc_maxwidth(&array, strlen(remote_prefix));
 
-	if (!format->format)
-		format->format = to_free = build_format(filter, maxwidth, remote_prefix);
+	if (!format->format) {
+		format->format = to_free = build_format(filter, maxwidth,
+							remote_prefix, 1);
+		here = current_worktree_path();
+		here_format = *format;
+		here_format.format = here_to_free = build_format(filter, maxwidth,
+								 remote_prefix, 0);
+	}
 	format->use_color = branch_use_color;
+	here_format.use_color = branch_use_color;
 
-	if (verify_ref_format(format))
+	if (verify_ref_format(format) ||
+	    (here && verify_ref_format(&here_format)))
 		die(_("unable to parse format string"));
 
 	filter_ahead_behind(the_repository, &array);
 	ref_array_sort(sorting, &array);
 
-	if (column_active(colopts)) {
-		struct strbuf out = STRBUF_INIT, err = STRBUF_INIT;
-
+	if (column_active(colopts))
 		assert(!filter->verbose && "--column and --verbose are incompatible");
 
-		for (i = 0; i < array.nr; i++) {
-			strbuf_reset(&err);
-			strbuf_reset(&out);
-			if (format_ref_array_item(array.items[i], format, &out, &err))
-				die("%s", err.buf);
+	for (i = 0; i < array.nr; i++) {
+		struct ref_array_item *item = array.items[i];
+		struct ref_format *f = format;
 
+		if (here && checked_out_here(item->refname, here))
+			f = &here_format;
+
+		strbuf_reset(&err);
+		strbuf_reset(&out);
+		if (format_ref_array_item(item, f, &out, &err))
+			die("%s", err.buf);
+
+		if (column_active(colopts))
 			/* format to a string_list to let print_columns() do its job */
 			string_list_append(output, out.buf);
+		else if (out.len || !format->array_opts.omit_empty) {
+			fwrite(out.buf, 1, out.len, stdout);
+			putchar('\n');
 		}
-
-		strbuf_release(&err);
-		strbuf_release(&out);
-	} else {
-		print_formatted_ref_array(&array, format);
 	}
 
+	strbuf_release(&err);
+	strbuf_release(&out);
 	ref_array_clear(&array);
 	free(to_free);
+	free(here_to_free);
+	free(here);
 }
 
 static void print_current_branch_name(void)
t/t3203-branch-output.sh +21 -1
index debfac5f26..5541f1429b 100755
@@ -456,6 +456,23 @@ test_expect_success 'branch being rebased in a worktree is marked' '
 	test_cmp expect actual
 '
 
+test_expect_success 'branch being rebased is not marked in its own worktree' '
+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebase_dir branch-two &&
+	(
+		cd rebase_dir &&
+		git commit --allow-empty -m rebase-me &&
+		test_must_fail git rebase -f -x false HEAD~1 &&
+		git branch --list rebasing >actual &&
+		echo "  rebasing" >expect &&
+		test_cmp expect actual &&
+		git branch -vv --list rebasing >actual &&
+		test_grep ! "$(pwd)" actual &&
+		git branch >actual &&
+		test_grep "^\* (no branch, rebasing rebasing)" actual
+	)
+'
+
 test_expect_success 'branch being bisected in a worktree is marked' '
 	test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
 	git worktree add -b bisecting bisect_dir branch-two &&
@@ -464,7 +481,10 @@ test_expect_success 'branch being bisected in a worktree is marked' '
 		git commit --allow-empty -m bisect-one &&
 		git commit --allow-empty -m bisect-two &&
 		git bisect start HEAD HEAD~2 &&
-		test_must_fail git symbolic-ref -q HEAD
+		test_must_fail git symbolic-ref -q HEAD &&
+		git branch --list bisecting >actual &&
+		echo "  bisecting" >expect &&
+		test_cmp expect actual
 	) &&
 	git branch --list bisecting >actual &&
 	echo "+ bisecting" >expect &&
Signature · 1 line
2.56.0
#37 lore raw

Re: [PATCH v4 4/4] branch: do not mark the branch the current worktree is rebasing

Hi Jasper

builtin/branch.c static const char *quote_literal_for_format(const char *s) · line 423

Quoted 13 lines · Jasper Mayone
builtin/branch.c +3 -1
index a613148fc7..b55a400217 100644
@@ -418,16 +418,28 @@ static const char *quote_literal_for_format(const char *s)
  	return buf.buf;
  }
 
-static char *build_format(struct ref_filter *filter, int maxwidth, const char *remote_prefix)
+/*
+ * With "show_worktree" unset, the format does not mark a branch that is
+ * checked out in a worktree, nor show the path of that worktree. It is

What is "It" here

builtin/branch.c static const char *quote_literal_for_format(const char *s) · line 425

Quoted 2 lines
builtin/branch.c +2 -0
+ * used for a branch that the current worktree is rebasing or bisecting,
+ * because the "(no branch, ...)" line already names it.

I'm not sure what is being named - do you mean "it already shows the branch name"?

In any case there are a lot of code changes here which is surprising for what I had hoped would be a simple tweak. If we added a '%(currentworktree)' format specifier, which should be relatively easy as we can use the hash map of branches to checked out worktrees to look up the worktree and check "wt->is_current" then

    %(if)%(worktreepath)%(then)%(if)%(currentworktree)%(then)%(else)+ 

%(else) %(end)%(end)

labels checked out worktrees with "+ " if they are not the current worktree.

Thanks

Phillip

Quoted 190 lines
builtin/branch.c +75 -22
+ */
+static char *build_format(struct ref_filter *filter, int maxwidth,
+			  const char *remote_prefix, int show_worktree)
  {
  	struct strbuf fmt = STRBUF_INIT;
  	struct strbuf local = STRBUF_INIT;
  	struct strbuf remote = STRBUF_INIT;
 
-	strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else)  %s%%(end)%%(end)",
-			branch_get_color(BRANCH_COLOR_CURRENT),
-			branch_get_color(BRANCH_COLOR_WORKTREE),
-			branch_get_color(BRANCH_COLOR_LOCAL));
+	if (show_worktree)
+		strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else)  %s%%(end)%%(end)",
+			    branch_get_color(BRANCH_COLOR_CURRENT),
+			    branch_get_color(BRANCH_COLOR_WORKTREE),
+			    branch_get_color(BRANCH_COLOR_LOCAL));
+	else
+		strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)  %s%%(end)",
+			    branch_get_color(BRANCH_COLOR_CURRENT),
+			    branch_get_color(BRANCH_COLOR_LOCAL));
  	strbuf_addf(&remote, "  %s",
  		    branch_get_color(BRANCH_COLOR_REMOTE));
 
@@ -447,8 +459,9 @@ static char *build_format(struct ref_filter *filter, int maxwidth, const char *r
 
  		if (filter->verbose > 1)
  		{
-			strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)",
-				    branch_get_color(BRANCH_COLOR_WORKTREE), branch_get_color(BRANCH_COLOR_RESET));
+			if (show_worktree)
+				strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)",
+					    branch_get_color(BRANCH_COLOR_WORKTREE), branch_get_color(BRANCH_COLOR_RESET));
  			strbuf_addf(&local, "%%(if)%%(upstream)%%(then)[%s%%(upstream:short)%s%%(if)%%(upstream:track)"
  				    "%%(then): %%(upstream:track,nobracket)%%(end)] %%(end)%%(contents:subject)",
  				    branch_get_color(BRANCH_COLOR_UPSTREAM), branch_get_color(BRANCH_COLOR_RESET));
@@ -477,6 +490,32 @@ static char *build_format(struct ref_filter *filter, int maxwidth, const char *r
  	return strbuf_detach(&fmt, NULL);
  }
 
+static char *current_worktree_path(void)
+{
+	struct worktree **worktrees = get_worktrees(the_repository);
+	char *path = NULL;
+
+	for (size_t i = 0; worktrees[i]; i++) {
+		if (worktrees[i]->is_current) {
+			path = xstrdup(worktrees[i]->path);
+			break;
+		}
+	}
+	free_worktrees(worktrees);
+	return path;
+}
+
+/*
+ * Is "refname" checked out in the worktree at "here", or is that
+ * worktree rebasing or bisecting it?
+ */
+static int checked_out_here(const char *refname, const char *here)
+{
+	const char *path = branch_checked_out_worktree(refname);
+
+	return path && !strcmp(path, here);
+}
+
  static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sorting,
  			   struct ref_format *format, struct string_list *output)
  {
@@ -485,6 +524,9 @@ static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sortin
  	int maxwidth = 0;
  	const char *remote_prefix = "";
  	char *to_free = NULL;
+	struct ref_format here_format = REF_FORMAT_INIT;
+	char *here_to_free = NULL, *here = NULL;
+	struct strbuf out = STRBUF_INIT, err = STRBUF_INIT;
 
  	/*
  	 * If we are listing more than just remote branches,
@@ -501,39 +543,54 @@ static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sortin
  	if (filter->verbose)
  		maxwidth = calc_maxwidth(&array, strlen(remote_prefix));
 
-	if (!format->format)
-		format->format = to_free = build_format(filter, maxwidth, remote_prefix);
+	if (!format->format) {
+		format->format = to_free = build_format(filter, maxwidth,
+							remote_prefix, 1);
+		here = current_worktree_path();
+		here_format = *format;
+		here_format.format = here_to_free = build_format(filter, maxwidth,
+								 remote_prefix, 0);
+	}
  	format->use_color = branch_use_color;
+	here_format.use_color = branch_use_color;
 
-	if (verify_ref_format(format))
+	if (verify_ref_format(format) ||
+	    (here && verify_ref_format(&here_format)))
  		die(_("unable to parse format string"));
 
  	filter_ahead_behind(the_repository, &array);
  	ref_array_sort(sorting, &array);
 
-	if (column_active(colopts)) {
-		struct strbuf out = STRBUF_INIT, err = STRBUF_INIT;
-
+	if (column_active(colopts))
  		assert(!filter->verbose && "--column and --verbose are incompatible");
 
-		for (i = 0; i < array.nr; i++) {
-			strbuf_reset(&err);
-			strbuf_reset(&out);
-			if (format_ref_array_item(array.items[i], format, &out, &err))
-				die("%s", err.buf);
+	for (i = 0; i < array.nr; i++) {
+		struct ref_array_item *item = array.items[i];
+		struct ref_format *f = format;
 
+		if (here && checked_out_here(item->refname, here))
+			f = &here_format;
+
+		strbuf_reset(&err);
+		strbuf_reset(&out);
+		if (format_ref_array_item(item, f, &out, &err))
+			die("%s", err.buf);
+
+		if (column_active(colopts))
  			/* format to a string_list to let print_columns() do its job */
  			string_list_append(output, out.buf);
+		else if (out.len || !format->array_opts.omit_empty) {
+			fwrite(out.buf, 1, out.len, stdout);
+			putchar('\n');
  		}
-
-		strbuf_release(&err);
-		strbuf_release(&out);
-	} else {
-		print_formatted_ref_array(&array, format);
  	}
 
+	strbuf_release(&err);
+	strbuf_release(&out);
  	ref_array_clear(&array);
  	free(to_free);
+	free(here_to_free);
+	free(here);
  }
 
  static void print_current_branch_name(void)
t/t3203-branch-output.sh +21 -1
index debfac5f26..5541f1429b 100755
@@ -456,6 +456,23 @@ test_expect_success 'branch being rebased in a worktree is marked' '
  	test_cmp expect actual
  '
 
+test_expect_success 'branch being rebased is not marked in its own worktree' '
+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebase_dir branch-two &&
+	(
+		cd rebase_dir &&
+		git commit --allow-empty -m rebase-me &&
+		test_must_fail git rebase -f -x false HEAD~1 &&
+		git branch --list rebasing >actual &&
+		echo "  rebasing" >expect &&
+		test_cmp expect actual &&
+		git branch -vv --list rebasing >actual &&
+		test_grep ! "$(pwd)" actual &&
+		git branch >actual &&
+		test_grep "^\* (no branch, rebasing rebasing)" actual
+	)
+'
+
  test_expect_success 'branch being bisected in a worktree is marked' '
  	test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
  	git worktree add -b bisecting bisect_dir branch-two &&
@@ -464,7 +481,10 @@ test_expect_success 'branch being bisected in a worktree is marked' '
  		git commit --allow-empty -m bisect-one &&
  		git commit --allow-empty -m bisect-two &&
  		git bisect start HEAD HEAD~2 &&
-		test_must_fail git symbolic-ref -q HEAD
+		test_must_fail git symbolic-ref -q HEAD &&
+		git branch --list bisecting >actual &&
+		echo "  bisecting" >expect &&
+		test_cmp expect actual
  	) &&
  	git branch --list bisecting >actual &&
  	echo "+ bisecting" >expect &&
#38 lore raw

Re: [PATCH v4 0/4] worktree: treat a branch being rebased or bisected as checked out

In reply to Jasper Mayone

Hi Jasper

This is moving in the right direction, but I think we want to use a hash to lookup which worktrees are checked out, rather than iterating over all worktress for every ref that we list.

Thanks

Phillip

Quoted 652 lines · Jasper Mayone

While a worktree is rebasing or bisecting a branch, its HEAD is detached. "git worktree add" and "git branch -d" already treat the branch as checked out there, but "git worktree remove" deletes such a worktree when its files are clean, and %(worktreepath) and "git branch" do not show which worktree has the branch.

Patch 1 makes "git worktree remove" refuse a worktree in the middle of an operation unless --force is given. Patch 2 documents how to read %(worktreepath) safely. Patch 3 makes %(worktreepath) name the worktree that is rebasing or bisecting a branch, and patch 4 keeps "git branch" from marking that branch with "+" in that worktree.

Changes since v3 [1]:

* Patch 1: also refuse a worktree that has CHERRY_PICK_HEAD or REVERT_HEAD, for a single cherry-pick or revert whose files are clean, with tests. The git-worktree documentation now lists the cases that need --force. The tests use a shared setup and subshells. Dropped the Helped-by trailer, as Phillip asked.

* Patch 2 is new. It adds the notes that Phillip suggested to the documentation of %(worktreepath): the path can contain a newline, and only one worktree is shown for a branch that is checked out in more than one.

* Patch 3: %(worktreepath) now uses a new branch.c function, branch_checked_out_worktree(), that reads the list that prepare_checked_out_branches() builds, in place of a copy of that code in ref-filter.c. ref-filter.c loses its own worktree map. The commit message explains why branches that "rebase --update-refs" will update are not included, and the change for the HEAD of a bare repository, which now has a test.

* Patch 4 is new. "git branch" no longer marks a branch with "+" in the worktree that is rebasing or bisecting it, because the "(no branch, ...)" line already names it.

[1] https://lore.kernel.org/git/[email protected]/

Jasper Mayone (4):
worktree remove: refuse a worktree in the middle of an operation
doc: for-each-ref: say how to read %(worktreepath) safely
ref-filter: name the worktree of a branch being rebased or bisected
branch: do not mark the branch the current worktree is rebasing

  Documentation/git-branch.adoc       |   6 +-
  Documentation/git-for-each-ref.adoc |  12 +++-
  Documentation/git-worktree.adoc     |  17 +++--
  branch.c                            |  13 ++++
  branch.h                            |   9 +++
  builtin/branch.c                    | 103 +++++++++++++++++++++-------
  builtin/worktree.c                  |  37 +++++++++-
  ref-filter.c                        |  74 +-------------------
  t/t2403-worktree-move.sh            |  94 +++++++++++++++++++++++++
  t/t3203-branch-output.sh            |  49 +++++++++++++
  t/t6302-for-each-ref-filter.sh      |  76 ++++++++++++++++++++
  11 files changed, 386 insertions(+), 104 deletions(-)

Range-diff against v3:
1: a79b69a0e4 ! 1: bca692b844 worktree remove: refuse a worktree in the middle of a rebase or bisect

     @@ Metadata
      Author: Jasper Mayone <[email protected]>
      
       ## Commit message ##
     -    worktree remove: refuse a worktree in the middle of a rebase or bisect
     +    worktree remove: refuse a worktree in the middle of an operation
      
     -    "git worktree remove" refuses a worktree with modified or untracked
     -    files unless --force is given, but it removes a worktree that is in
     -    the middle of a rebase, a "git am" session, a bisect or a cherry-pick
     -    or revert sequence when its files happen to be clean. The state of
     -    that operation lives in the worktree's own $GIT_DIR, so it is lost
     -    with the worktree. A rebase stopped at an "edit" or "break" line, an
     -    "exec" that failed, or a cherry-pick sequence after a conflict was
     -    resolved and committed is clean in this sense and still has work in
     -    progress.
     +    "git worktree remove" refuses to remove a worktree with modified or
     +    untracked files unless --force is given, but it removes a worktree
     +    that is in the middle of a rebase, a "git am" session, a bisect, a
     +    cherry-pick or a revert when its files happen to be clean. The state
     +    of that operation lives in the worktree's own $GIT_DIR, so it is lost
     +    with the worktree. Examples of such a clean worktree are a rebase
     +    stopped at an "edit" or "break" line or after a failed "exec", a
     +    cherry-pick sequence after a conflict was resolved and committed, and
     +    a single cherry-pick or revert whose conflict was resolved to the
     +    current contents, which leaves CHERRY_PICK_HEAD or REVERT_HEAD behind.
      
          Treat such a worktree as unclean: refuse to remove it unless --force
          is given, and name the operation in the message.
     @@ Commit message
          worktree, which is only done when the directory exists.
      
          Reported-by: D. Ben Knoble <[email protected]>
     -    Helped-by: Phillip Wood <[email protected]>
          Signed-off-by: Jasper Mayone <[email protected]>
      
       ## Documentation/git-worktree.adoc ##
      @@ Documentation/git-worktree.adoc: the new working tree location.
     +
       `remove`::
       
     - Remove a worktree. Only clean worktrees (no untracked files and no
     +-Remove a worktree. Only clean worktrees (no untracked files and no
      -modification in tracked files) can be removed. Unclean worktrees or ones
      -with submodules can be removed with `--force`. The main worktree cannot be
      -removed.
     -+modification in tracked files) can be removed. A worktree in the middle
     -+of a rebase, a `git am` session, a bisect or a cherry-pick or revert
     -+sequence is not clean either, because removing it loses that state. Unclean worktrees or ones with submodules
     -+can be removed with `--force`. The main worktree cannot be removed.
     ++Remove a worktree. The main worktree cannot be removed. Without
     ++`--force`, a worktree is not removed when:
     +++
     ++--
     ++* it has untracked files or modifications in tracked files,
     ++* it has submodules, or
     ++* it is in the middle of a rebase, a `git am` session, a bisect, a
     ++  cherry-pick or a revert, because removing it loses the state of that
     ++  operation.
     ++--
       
       `repair [<path>...]`::
       
     @@ Documentation/git-worktree.adoc: twice. If the destination is already assigned t
       allows the move to proceed; use `--force` twice if the destination is locked.
       +
      -`remove` refuses to remove an unclean worktree unless `--force` is used.
     -+`remove` refuses to remove an unclean worktree, or one in the middle of a
     -+rebase, `git am` session, bisect, or cherry-pick or revert sequence,
     -+unless `--force` is used.
     ++`remove` refuses to remove a worktree in the cases listed under
     ++`remove` above unless `--force` is used.
       To remove a locked worktree, specify `--force` twice.
       
       `-b <new-branch>`::
     @@ builtin/worktree.c: static void check_clean_worktree(struct worktree *wt,
       }
       
      +/*
     -+ * A rebase, "git am", bisect or cherry-pick/revert sequence keeps its
     -+ * state in the worktree's own $GIT_DIR, and removing the worktree
     -+ * throws that away even when "git status" says the files are clean.
     ++ * A rebase, "git am", bisect, cherry-pick or revert keeps its state in
     ++ * the worktree's own $GIT_DIR, and removing the worktree throws that
     ++ * away even when "git status" says the files are clean.
      + */
      +static void check_no_operation_in_progress(struct worktree *wt,
      +					   const char *original_path)
     @@ builtin/worktree.c: static void check_clean_worktree(struct worktree *wt,
      +		die(_("'%s' is in the middle of a bisect, use --force to delete it"),
      +		    original_path);
      +	wt_status_state_free_buffers(&state);
     ++	if (refs_ref_exists(get_worktree_ref_store(wt), "CHERRY_PICK_HEAD"))
     ++		die(_("'%s' is in the middle of a cherry-pick, use --force to delete it"),
     ++		    original_path);
     ++	if (refs_ref_exists(get_worktree_ref_store(wt), "REVERT_HEAD"))
     ++		die(_("'%s' is in the middle of a revert, use --force to delete it"),
     ++		    original_path);
      +	if (is_directory(worktree_git_path(wt, "sequencer")))
      +		die(_("'%s' is in the middle of a cherry-pick or revert, use --force to delete it"),
      +		    original_path);
     @@ t/t2403-worktree-move.sh: test_expect_success 'move worktree with relative path
       	test_cmp expect .git/worktrees/absolute/gitdir
       '
       
     ++test_expect_success 'setup commits that conflict for am, cherry-pick and revert' '
     ++	git worktree add --detach conflict-setup init &&
     ++	(
     ++		cd conflict-setup &&
     ++		test_commit base conflict.t base &&
     ++		git switch --detach init &&
     ++		test_commit side conflict.t side &&
     ++		test_commit side-two
     ++	) &&
     ++	git worktree remove conflict-setup
     ++'
     ++
      +test_expect_success 'remove worktree in the middle of a rebase' '
      +	test_when_finished "rm -rf mid-rebase; git worktree prune" &&
     -+	git worktree add --detach mid-rebase init &&
     -+	test_commit -C mid-rebase rebase-me &&
     ++	git worktree add --detach mid-rebase side &&
      +	test_must_fail git -C mid-rebase rebase -f -x false init &&
      +	test_must_fail git worktree remove mid-rebase 2>err &&
      +	test_grep "in the middle of a rebase" err &&
     @@ t/t2403-worktree-move.sh: test_expect_success 'move worktree with relative path
      +
      +test_expect_success 'remove worktree in the middle of an am session' '
      +	test_when_finished "rm -rf mid-am patch; git worktree prune" &&
     -+	git worktree add --detach mid-am init &&
     -+	test_commit -C mid-am am-me &&
     -+	git -C mid-am format-patch -1 --stdout >patch &&
     -+	git -C mid-am reset --hard init &&
     -+	echo conflict >mid-am/am-me.t &&
     -+	git -C mid-am add am-me.t &&
     -+	git -C mid-am commit -m conflict &&
     -+	test_must_fail git -C mid-am am ../patch &&
     -+	git -C mid-am reset --hard &&
     ++	git format-patch -1 --stdout side >patch &&
     ++	git worktree add --detach mid-am base &&
     ++	(
     ++		cd mid-am &&
     ++		test_must_fail git am ../patch &&
     ++		git reset --hard
     ++	) &&
      +	test_must_fail git worktree remove mid-am 2>err &&
      +	test_grep "in the middle of an am session" err &&
      +	git worktree remove --force mid-am
     @@ t/t2403-worktree-move.sh: test_expect_success 'move worktree with relative path
      +
      +test_expect_success 'remove worktree in the middle of a bisect' '
      +	test_when_finished "rm -rf mid-bisect; git worktree prune" &&
     -+	git worktree add --detach mid-bisect init &&
     -+	test_commit -C mid-bisect bisect-one &&
     -+	test_commit -C mid-bisect bisect-two &&
     -+	git -C mid-bisect bisect start HEAD init &&
     ++	git worktree add --detach mid-bisect side-two &&
     ++	git -C mid-bisect bisect start side-two init &&
      +	test_must_fail git worktree remove mid-bisect 2>err &&
      +	test_grep "in the middle of a bisect" err &&
      +	git worktree remove --force mid-bisect
      +'
      +
     -+test_expect_success 'remove worktree in the middle of a cherry-pick sequence' '
     ++test_expect_success 'remove worktree in the middle of a cherry-pick' '
      +	test_when_finished "rm -rf mid-pick; git worktree prune" &&
     -+	git worktree add --detach mid-pick init &&
     -+	git -C mid-pick switch -c pick-src &&
     -+	test_commit -C mid-pick pick-one &&
     -+	test_commit -C mid-pick pick-two &&
     -+	git -C mid-pick switch --detach init &&
     -+	echo conflict >mid-pick/pick-one.t &&
     -+	git -C mid-pick add pick-one.t &&
     -+	git -C mid-pick commit -m conflict &&
     -+	test_must_fail git -C mid-pick cherry-pick pick-src~1 pick-src &&
     -+	git -C mid-pick checkout --theirs pick-one.t &&
     -+	git -C mid-pick add pick-one.t &&
     -+	git -C mid-pick commit --no-edit &&
     -+	test_path_is_dir .git/worktrees/mid-pick/sequencer &&
     ++	git worktree add --detach mid-pick base &&
     ++	(
     ++		cd mid-pick &&
     ++		test_must_fail git cherry-pick side &&
     ++		git checkout --ours conflict.t &&
     ++		git add conflict.t &&
     ++		git rev-parse --verify CHERRY_PICK_HEAD
     ++	) &&
     ++	test_path_is_missing .git/worktrees/mid-pick/sequencer &&
      +	test_must_fail git worktree remove mid-pick 2>err &&
     -+	test_grep "in the middle of a cherry-pick or revert" err &&
     ++	test_grep "in the middle of a cherry-pick," err &&
      +	git worktree remove --force mid-pick
      +'
     ++
     ++test_expect_success 'remove worktree in the middle of a revert' '
     ++	test_when_finished "rm -rf mid-revert; git worktree prune" &&
     ++	git worktree add --detach mid-revert base &&
     ++	(
     ++		cd mid-revert &&
     ++		test_must_fail git revert side &&
     ++		git checkout --ours conflict.t &&
     ++		git add conflict.t &&
     ++		git rev-parse --verify REVERT_HEAD
     ++	) &&
     ++	test_path_is_missing .git/worktrees/mid-revert/sequencer &&
     ++	test_must_fail git worktree remove mid-revert 2>err &&
     ++	test_grep "in the middle of a revert" err &&
     ++	git worktree remove --force mid-revert
     ++'
     ++
     ++test_expect_success 'remove worktree in the middle of a cherry-pick sequence' '
     ++	test_when_finished "rm -rf mid-pick-seq; git worktree prune" &&
     ++	git worktree add --detach mid-pick-seq base &&
     ++	(
     ++		cd mid-pick-seq &&
     ++		test_must_fail git cherry-pick side side-two &&
     ++		git checkout --theirs conflict.t &&
     ++		git add conflict.t &&
     ++		git commit --no-edit
     ++	) &&
     ++	test_path_is_dir .git/worktrees/mid-pick-seq/sequencer &&
     ++	test_must_fail git worktree remove mid-pick-seq 2>err &&
     ++	test_grep "in the middle of a cherry-pick or revert" err &&
     ++	git worktree remove --force mid-pick-seq
     ++'
      +
       test_done
-:  ---------- > 2:  39eb92d441 doc: for-each-ref: say how to read %(worktreepath) safely
2:  0cd13347e1 ! 3:  990a19fd11 ref-filter: name the worktree of a branch being rebased or bisected
     @@ Commit message
      
          The rest of Git already treats that branch as checked out: "git
          worktree add" and "git branch -d" refuse it, because finishing the
     -    rebase or bisect will check it out again. "git worktree list" shows
     -    such a worktree as "(detached HEAD)", so %(worktreepath) is the only
     -    place a script could find out which worktree is working on the
     -    branch.
     +    rebase or bisect will check it out again. But no command shows which
     +    worktree is working on the branch: "git worktree list" shows such a
     +    worktree as "(detached HEAD)", and %(worktreepath) is empty.
      
     -    Also map the branch that a worktree is rebasing or bisecting to that
     -    worktree, as prepare_checked_out_branches() in branch.c does.
     -    Branches that "rebase --update-refs" will update are not mapped: that
     -    worktree has not checked them out, it only moves them when the rebase
     -    is done.
     +    branch.c already knows the answer, as prepare_checked_out_branches()
     +    records the branch that each worktree has checked out, is rebasing or
     +    is bisecting. Add branch_checked_out_worktree() to look a branch up in
     +    that list, and use it for %(worktreepath) in place of the map that
     +    ref-filter.c builds from the HEAD of each worktree.
      
     -    As a result "git branch" marks such a branch with "+", also when it
     -    runs in the worktree that is rebasing or bisecting it, where it shows
     -    both "* (no branch, rebasing topic)" and "+ topic". Document that.
     +    The new function skips the branches that "rebase --update-refs" will
     +    update. branch_checked_out() includes them, so that they cannot be
     +    checked out or deleted during the rebase, but the worktree that runs
     +    the rebase has not checked them out. %(worktreepath) therefore stays
     +    empty for them, unlike branch_checked_out().
     +
     +    This also changes the result for a bare repository: its HEAD names a
     +    branch, and %(worktreepath) used to give the path of the bare
     +    repository for that branch. "git branch" in a linked worktree marked
     +    the branch with "+", although no worktree has it checked out and "git
     +    worktree add" lets you check it out. prepare_checked_out_branches()
     +    skips bare repositories, so %(worktreepath) is now empty for that
     +    branch and "git branch" no longer marks it.
      
          Reported-by: Kristoffer Haugsbakk <[email protected]>
          Helped-by: Phillip Wood <[email protected]>
     @@ Documentation/git-branch.adoc: DESCRIPTION
       branches are listed; the current branch will be highlighted in green and
       marked with an asterisk.  Any branches checked out in linked worktrees will
      -be highlighted in cyan and marked with a plus sign. Option `-r` causes the
     +-remote-tracking branches to be listed,
      +be highlighted in cyan and marked with a plus sign. A branch that a
     -+worktree is rebasing or bisecting counts as checked out there, so it is
     -+marked in the same way, also in the worktree that is rebasing or
     -+bisecting it. Option `-r` causes the
     - remote-tracking branches to be listed,
     ++worktree is rebasing or bisecting counts as checked out in that
     ++worktree, so the other worktrees mark it in the same way. Option `-r`
     ++causes the remote-tracking branches to be listed,
       and option `-a` shows both local and remote branches.
       
     + If a `<pattern>`
      
       ## Documentation/git-for-each-ref.adoc ##
      @@ Documentation/git-for-each-ref.adoc: but if used together the last option is selected.
     @@ Documentation/git-for-each-ref.adoc: but if used together the last option is sel
      -	out, if it is checked out in any linked worktree. Empty string
      +	out, if it is checked out in any linked worktree. A branch that
      +	a worktree is rebasing or bisecting counts as checked out there,
     -+	although that worktree's `HEAD` is detached. Empty string
     - 	otherwise.
     -
     - `ahead-behind:<commit-ish>`::
     ++	although that worktree's `HEAD` is detached. A branch that
     ++	`git rebase --update-refs` will update does not. Empty string
     + 	otherwise. If the ref is checked out in more than one worktree,
     + 	only one of them is shown. The path can contain a newline, so
     + 	use one of the quoting options such as `--shell`, or follow
      
     - ## ref-filter.c ##
     -@@ ref-filter.c: static struct expand_data {
     -
     - struct ref_to_worktree_entry {
     - 	struct hashmap_entry ent;
     --	struct worktree *wt; /* key is wt->head_ref */
     -+	struct worktree *wt;
     -+	char refname[FLEX_ARRAY]; /* the key */
     - };
     -
     - static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
     -@@ ref-filter.c: static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
     - 	e = container_of(eptr, const struct ref_to_worktree_entry, ent);
     - 	k = container_of(kptr, const struct ref_to_worktree_entry, ent);
     -
     --	return strcmp(e->wt->head_ref,
     --		keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
     -+	return strcmp(e->refname,
     -+		keydata_aka_refname ? keydata_aka_refname : k->refname);
     + ## branch.c ##
     +@@ branch.c: const char *branch_checked_out(const char *refname)
     + 	return strmap_get(&current_checked_out_branches, refname);
       }
       
     - static struct ref_to_worktree_map {
     ++const char *branch_checked_out_worktree(const char *refname)
     ++{
     ++	const char *path = NULL;
     ++
     ++	prepare_checked_out_branches();
     ++	for (size_t i = 0; i < checked_out_branches_nr; i++) {
     ++		if (checked_out_branches[i].kind != BRANCH_CHECKOUT_KIND_UPDATE_REF &&
     ++		    !strcmp(refname, checked_out_branches[i].refname))
     ++			path = checked_out_branches[i].path;
     ++	}
     ++	return path;
     ++}
     ++
     + const char *branch_bisecting(const char *refname)
     + {
     + 	prepare_checked_out_branches();
     +
     + ## branch.h ##
     +@@ branch.h: void create_branches_recursively(struct repository *r, const char *name,
     +  */
     + const char *branch_checked_out(const char *refname);
     +
     ++/*
     ++ * If a worktree has the branch 'refname' checked out, or is rebasing or
     ++ * bisecting it, return the path of that worktree, or of the last one if
     ++ * there are more. Otherwise return NULL. Unlike branch_checked_out(),
     ++ * this ignores the branches that "git rebase --update-refs" will
     ++ * update, because no worktree has them checked out.
     ++ */
     ++const char *branch_checked_out_worktree(const char *refname);
     ++
     + /*
     +  * If the branch at 'refname' is currently used for bisecting in a
     +  * worktree, then return the path to that worktree.
     +
     + ## ref-filter.c ##
     +@@
     + #define DISABLE_SIGN_COMPARE_WARNINGS
     +
     + #include "git-compat-util.h"
     ++#include "branch.h"
     + #include "environment.h"
     + #include "gettext.h"
     + #include "config.h"
     +@@ ref-filter.c: static struct expand_data {
     + 	struct object_info info;
     + } oi, oi_deref;
     +
     +-struct ref_to_worktree_entry {
     +-	struct hashmap_entry ent;
     +-	struct worktree *wt; /* key is wt->head_ref */
     +-};
     +-
     +-static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
     +-				      const struct hashmap_entry *eptr,
     +-				      const struct hashmap_entry *kptr,
     +-				      const void *keydata_aka_refname)
     +-{
     +-	const struct ref_to_worktree_entry *e, *k;
     +-
     +-	e = container_of(eptr, const struct ref_to_worktree_entry, ent);
     +-	k = container_of(kptr, const struct ref_to_worktree_entry, ent);
     +-
     +-	return strcmp(e->wt->head_ref,
     +-		keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
     +-}
     +-
     +-static struct ref_to_worktree_map {
     +-	struct hashmap map;
     +-	struct worktree **worktrees;
     +-} ref_to_worktree_map;
     +-
     + /*
     +  * The enum atom_type is used as the index of valid_atom array.
     +  * In the atom parsing stage, it will be passed to used_atom.atom_type
      @@ ref-filter.c: static int get_object(struct ref_array_item *ref, int deref,
       	return ret;
       }
       
     -+static void add_worktree_entry(struct hashmap *map, struct worktree *wt,
     -+			       const char *refname)
     -+{
     -+	struct ref_to_worktree_entry *entry;
     -+
     -+	FLEX_ALLOC_STR(entry, refname, refname);
     -+	entry->wt = wt;
     -+	hashmap_entry_init(&entry->ent, strhash(refname));
     -+	hashmap_add(map, &entry->ent);
     -+}
     -+
     -+/*
     -+ * Map each branch to the worktree that has it checked out. A worktree
     -+ * that is rebasing or bisecting a branch has it checked out, too,
     -+ * even though its HEAD may be detached, as for
     -+ * prepare_checked_out_branches() in branch.c.
     -+ */
     - static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
     - {
     +-static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
     +-{
      -	int i;
     -+	struct strbuf ref = STRBUF_INIT;
     -
     +-
      -	for (i = 0; worktrees[i]; i++) {
      -		if (worktrees[i]->head_ref) {
      -			struct ref_to_worktree_entry *entry;
     @@ ref-filter.c: static int get_object(struct ref_array_item *ref, int deref,
      -			entry->wt = worktrees[i];
      -			hashmap_entry_init(&entry->ent,
      -					strhash(worktrees[i]->head_ref));
     -+	for (size_t i = 0; worktrees[i]; i++) {
     -+		struct worktree *wt = worktrees[i];
     -+		struct wt_status_state state = { 0 };
     -
     +-
      -			hashmap_add(map, &entry->ent);
     -+		if (wt->is_bare)
     -+			continue;
     -+
     -+		if (wt->head_ref)
     -+			add_worktree_entry(map, wt, wt->head_ref);
     -+
     -+		if (wt_status_check_rebase(wt, &state) &&
     -+		    (state.rebase_in_progress ||
     -+		     state.rebase_interactive_in_progress) &&
     -+		    state.branch) {
     -+			strbuf_reset(&ref);
     -+			strbuf_addf(&ref, "refs/heads/%s", state.branch);
     -+			add_worktree_entry(map, wt, ref.buf);
     - 		}
     -+		wt_status_state_free_buffers(&state);
     -+
     -+		if (wt_status_check_bisect(wt, &state) &&
     -+		    state.bisecting_from) {
     -+			strbuf_reset(&ref);
     -+			strbuf_addf(&ref, "refs/heads/%s", state.bisecting_from);
     -+			add_worktree_entry(map, wt, ref.buf);
     -+		}
     -+		wt_status_state_free_buffers(&state);
     - 	}
     -+	strbuf_release(&ref);
     +-		}
     +-	}
     +-}
     +-
     +-static void lazy_init_worktree_map(void)
     +-{
     +-	if (ref_to_worktree_map.worktrees)
     +-		return;
     +-
     +-	ref_to_worktree_map.worktrees = get_worktrees(the_repository);
     +-	hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
     +-	populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
     +-}
     +-
     + static char *get_worktree_path(const struct ref_array_item *ref)
     + {
     +-	struct hashmap_entry entry, *e;
     +-	struct ref_to_worktree_entry *lookup_result;
     ++	const char *path = branch_checked_out_worktree(ref->refname);
     +
     +-	lazy_init_worktree_map();
     +-
     +-	hashmap_entry_init(&entry, strhash(ref->refname));
     +-	e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
     +-
     +-	if (!e)
     +-		return xstrdup("");
     +-
     +-	lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
     +-
     +-	return xstrdup(lookup_result->wt->path);
     ++	return xstrdup(path ? path : "");
     + }
     +
     + /*
     +@@ ref-filter.c: void ref_array_clear(struct ref_array *array)
     + 	FREE_AND_NULL(used_atom);
     + 	used_atom_cnt = 0;
     +
     +-	if (ref_to_worktree_map.worktrees) {
     +-		hashmap_clear_and_free(&(ref_to_worktree_map.map),
     +-					struct ref_to_worktree_entry, ent);
     +-		free_worktrees(ref_to_worktree_map.worktrees);
     +-		ref_to_worktree_map.worktrees = NULL;
     +-	}
     +-
     + 	FREE_AND_NULL(array->counts);
       }
       
     - static void lazy_init_worktree_map(void)
      
       ## t/t3203-branch-output.sh ##
      @@ t/t3203-branch-output.sh: test_expect_success 'worktree colors correct' '
     @@ t/t3203-branch-output.sh: test_expect_success 'worktree colors correct' '
      +test_expect_success 'branch being rebased in a worktree is marked' '
      +	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
      +	git worktree add -b rebasing rebase_dir branch-two &&
     -+	git -C rebase_dir commit --allow-empty -m rebase-me &&
     -+	test_must_fail git -C rebase_dir rebase -f -x false HEAD~1 &&
     -+	test_must_fail git -C rebase_dir symbolic-ref -q HEAD &&
     ++	(
     ++		cd rebase_dir &&
     ++		git commit --allow-empty -m rebase-me &&
     ++		test_must_fail git rebase -f -x false HEAD~1 &&
     ++		test_must_fail git symbolic-ref -q HEAD
     ++	) &&
      +	git branch --list rebasing >actual &&
      +	echo "+ rebasing" >expect &&
      +	test_cmp expect actual
      +'
      +
     -+test_expect_success 'branch being rebased is marked in its own worktree' '
     -+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
     -+	git worktree add -b rebasing rebase_dir branch-two &&
     -+	git -C rebase_dir commit --allow-empty -m rebase-me &&
     -+	test_must_fail git -C rebase_dir rebase -f -x false HEAD~1 &&
     -+	git -C rebase_dir branch --list rebasing >actual &&
     -+	echo "+ rebasing" >expect &&
     -+	test_cmp expect actual &&
     -+	git -C rebase_dir branch >actual &&
     -+	test_grep "^\* (no branch, rebasing rebasing)" actual
     -+'
     -+
      +test_expect_success 'branch being bisected in a worktree is marked' '
      +	test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
      +	git worktree add -b bisecting bisect_dir branch-two &&
     -+	git -C bisect_dir commit --allow-empty -m bisect-one &&
     -+	git -C bisect_dir commit --allow-empty -m bisect-two &&
     -+	git -C bisect_dir bisect start HEAD HEAD~2 &&
     -+	test_must_fail git -C bisect_dir symbolic-ref -q HEAD &&
     ++	(
     ++		cd bisect_dir &&
     ++		git commit --allow-empty -m bisect-one &&
     ++		git commit --allow-empty -m bisect-two &&
     ++		git bisect start HEAD HEAD~2 &&
     ++		test_must_fail git symbolic-ref -q HEAD
     ++	) &&
      +	git branch --list bisecting >actual &&
      +	echo "+ bisecting" >expect &&
      +	test_cmp expect actual
     @@ t/t6302-for-each-ref-filter.sh: test_expect_success 'validate worktree atom' '
      +	git for-each-ref --format="%(worktreepath)" refs/heads/ >actual &&
      +	test_grep ! detached-rebase actual
      +'
     ++
     ++test_expect_success 'worktree atom ignores the HEAD of a bare repository' '
     ++	test_when_finished "rm -rf bare.git bare-wt" &&
     ++	git clone --bare . bare.git &&
     ++	git -C bare.git symbolic-ref HEAD refs/heads/main &&
     ++	git -C bare.git worktree add --detach ../bare-wt main &&
     ++	git -C bare.git for-each-ref --format="%(worktreepath)" refs/heads/main >actual &&
     ++	echo >expect &&
     ++	test_cmp expect actual &&
     ++	git -C bare-wt branch --list main >actual &&
     ++	echo "  main" >expect &&
     ++	test_cmp expect actual
     ++'
      +
       test_expect_success 'start after with empty value' '
       	cat >expect <<-\EOF &&

-: ---------- > 4: 56e29c448f branch: do not mark the branch the current worktree is rebasing

#39 lore raw

v5 cover worktree: treat a branch being rebased or bisected as checked out

In reply to Jasper Mayone

While a worktree is rebasing or bisecting a branch, its HEAD is detached. "git worktree add" and "git branch -d" already treat the branch as checked out there, but "git worktree remove" deletes such a worktree when its files are clean, and %(worktreepath) and "git branch" do not show which worktree has the branch.

Patch 1 makes "git worktree remove" refuse a worktree in the middle of an operation unless --force is given. Patch 2 documents how to read %(worktreepath) safely. Patch 3 makes %(worktreepath) name the worktree that is rebasing or bisecting a branch. Patch 4 adds %(currentworktree), and patch 5 uses it so that "git branch" does not mark that branch with "+" in the worktree that is rebasing it.

Changes since v4 [1]:

* Patch 1: each item in the list of cases that need --force is now a complete sentence, and all the commands are in the same font, as Phillip asked. Ben was happy with the old wording, and I hope this suits both of you.

* Patch 2: no change.

* Patch 3: branch.c records the branches in a map, so branch_checked_out_worktree() is one map lookup in place of a loop over every worktree for each ref.

* Patch 4 is new. It adds %(currentworktree), which Phillip suggested. It uses a second map in branch.c for the branches that the current worktree has.

* Patch 5 replaces v4's patch 4. The default "git branch" format now uses %(currentworktree), so print_ref_list() is unchanged and the patch is a few lines in build_format().

[1] https://lore.kernel.org/git/[email protected]/

Jasper Mayone (5):
worktree remove: refuse a worktree in the middle of an operation
doc: for-each-ref: say how to read %(worktreepath) safely
ref-filter: name the worktree of a branch being rebased or bisected
ref-filter: add %(currentworktree)
branch: do not mark the branch the current worktree is rebasing

 Documentation/git-branch.adoc       |  6 +-
 Documentation/git-for-each-ref.adoc | 19 +++++-
 Documentation/git-worktree.adoc     | 17 +++--
 branch.c                            | 33 ++++++++--
 branch.h                            | 16 +++++
 builtin/branch.c                    | 10 ++-
 builtin/worktree.c                  | 37 ++++++++++-
 ref-filter.c                        | 84 ++++---------------------
 t/t2403-worktree-move.sh            | 94 ++++++++++++++++++++++++++++
 t/t3203-branch-output.sh            | 49 +++++++++++++++
 t/t6302-for-each-ref-filter.sh      | 97 +++++++++++++++++++++++++++++
 11 files changed, 373 insertions(+), 89 deletions(-)

Range-diff against v4:
1: bca692b844 ! 1: 69668bf9b1 worktree remove: refuse a worktree in the middle of an operation
@@ Documentation/git-worktree.adoc: the new working tree location.
-with submodules can be removed with --force. The main worktree cannot be -removed.
+Remove a worktree. The main worktree cannot be removed. Without
-+--force, a worktree is not removed when:
++--force, a worktree is not removed in these cases:
++
+--
-+* it has untracked files or modifications in tracked files,
-+* it has submodules, or
-+* it is in the middle of a rebase, a git am session, a bisect, a
-+ cherry-pick or a revert, because removing it loses the state of that
-+ operation.
++* The worktree has untracked files or modifications in tracked files.
++* The worktree has submodules.
++* The worktree is in the middle of a git rebase, git am,
++ git bisect, git cherry-pick or git revert. Removing the
++ worktree would lose the state of that operation.
+--

repair [<path>...]::

2:  39eb92d441 = 2:  35035d30e2 doc: for-each-ref: say how to read %(worktreepath) safely
3:  990a19fd11 ! 3:  4484dfff22 ref-filter: name the worktree of a branch being rebased or bisected

@@ Commit message

branch.c already knows the answer, as prepare_checked_out_branches() records the branch that each worktree has checked out, is rebasing or
- is bisecting. Add branch_checked_out_worktree() to look a branch up in
- that list, and use it for %(worktreepath) in place of the map that
- ref-filter.c builds from the HEAD of each worktree.
+ is bisecting. Record those branches in a map as well, add
+ branch_checked_out_worktree() to look a branch up in it, and use that
+ for %(worktreepath) in place of the map that ref-filter.c builds from
+ the HEAD of each worktree.

The new function skips the branches that "rebase --update-refs" will update. branch_checked_out() includes them, so that they cannot be
@@ Documentation/git-for-each-ref.adoc: but if used together the last option is sel
use one of the quoting options such as --shell, or follow

## branch.c ##
+@@ branch.c: int validate_branchname(const char *name, struct strbuf *ref) +
+ static int initialized_checked_out_branches;
+ static struct strmap current_checked_out_branches = STRMAP_INIT;
++/* Like current_checked_out_branches, without the "update-ref" branches. */ ++static struct strmap checked_out_worktrees = STRMAP_INIT;
+
+ enum branch_checkout_kind {
+ BRANCH_CHECKOUT_KIND_CHECKOUT,
+@@ branch.c: static void register_checked_out_branch(const char *prefix, const char *name,
+ checked_out_branches_nr++;
+
+ strmap_put(&current_checked_out_branches, refname, path_copy);
++ if (kind != BRANCH_CHECKOUT_KIND_UPDATE_REF)
++ strmap_put(&checked_out_worktrees, refname, path_copy);
+ }
+
+ static void prepare_checked_out_branches(void)
@@ branch.c: const char *branch_checked_out(const char *refname)
return strmap_get(&current_checked_out_branches, refname);
}

+const char *branch_checked_out_worktree(const char *refname)
+{
-+ const char *path = NULL;
-+
+ prepare_checked_out_branches();
-+ for (size_t i = 0; i < checked_out_branches_nr; i++) {
-+ if (checked_out_branches[i].kind != BRANCH_CHECKOUT_KIND_UPDATE_REF &&
-+ !strcmp(refname, checked_out_branches[i].refname))
-+ path = checked_out_branches[i].path;
-+ }
-+ return path;
++ return strmap_get(&checked_out_worktrees, refname);
+}
+
const char *branch_bisecting(const char *refname)
4: 56e29c448f ! 4: 944ce70324 branch: do not mark the branch the current worktree is rebasing
@@ Metadata
Author: Jasper Mayone <[email protected]>

## Commit message ##
- branch: do not mark the branch the current worktree is rebasing
+ ref-filter: add %(currentworktree)

- Since the previous commit, "git branch" marks a branch with "+" when a
- worktree is rebasing or bisecting it. In that worktree itself, the
- list already starts with "* (no branch, rebasing topic)", so the
- "+ topic" line below it says the same thing twice.
+ %(worktreepath) names the worktree that has a branch checked out, or
+ is rebasing or bisecting it, but a format cannot tell if that worktree
+ is the current one. Comparing %(worktreepath) with a fixed path in
+ %(if:equals=...) does not work for every path, because a ")" ends the
+ atom.

- The default format cannot tell that apart: %(worktreepath) gives the
- same path either way, and comparing it with %(if:equals=...) is not
- safe because a path, or a branch name, can contain the ")" that ends
- the atom. So build a second format that has no "+" marker and no
- "(path)" for -vv, and use it for each branch that
- branch_checked_out_worktree() maps to the current worktree. A branch
- that is checked out normally in the current worktree also gets that
- format, but %(HEAD) still marks it with "*" and -vv already hides
- its path, so its output does not change.
+ Add %(currentworktree), which gives the path of the current worktree
+ when that worktree has the branch, and an empty string otherwise.
+ branch.c records these branches when it reads the worktrees, in a
+ second map next to the one that %(worktreepath) uses, so the lookup is
+ one map lookup per ref.

- To pick a format for each branch, print_ref_list() now formats the
- branches itself in place of print_formatted_ref_array(), keeping
- --omit-empty. A format given with --format is used for every branch,
- as before.
+ The next commit uses it in "git branch".

- ## builtin/branch.c ##
-@@ builtin/branch.c: static const char *quote_literal_for_format(const char *s)
- return buf.buf;
- }
+ ## Documentation/git-for-each-ref.adoc ##
+@@ Documentation/git-for-each-ref.adoc: but if used together the last option is selected.
+ the NUL after the path and then for the LF that ends each
+ record.

--static char *build_format(struct ref_filter *filter, int maxwidth, const char *remote_prefix) -+/*
-+ * With "show_worktree" unset, the format does not mark a branch that is
-+ * checked out in a worktree, nor show the path of that worktree. It is
-+ * used for a branch that the current worktree is rebasing or bisecting,
-+ * because the "(no branch, ...)" line already names it.
-+ */
-+static char *build_format(struct ref_filter *filter, int maxwidth,
-+ const char *remote_prefix, int show_worktree)
- {
- struct strbuf fmt = STRBUF_INIT;
- struct strbuf local = STRBUF_INIT;
- struct strbuf remote = STRBUF_INIT;
-
-- strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else) %s%%(end)%%(end)",
-- branch_get_color(BRANCH_COLOR_CURRENT),
-- branch_get_color(BRANCH_COLOR_WORKTREE),
-- branch_get_color(BRANCH_COLOR_LOCAL));
-+ if (show_worktree)
-+ strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else) %s%%(end)%%(end)",
-+ branch_get_color(BRANCH_COLOR_CURRENT),
-+ branch_get_color(BRANCH_COLOR_WORKTREE),
-+ branch_get_color(BRANCH_COLOR_LOCAL));
-+ else
-+ strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else) %s%%(end)",
-+ branch_get_color(BRANCH_COLOR_CURRENT),
-+ branch_get_color(BRANCH_COLOR_LOCAL));
- strbuf_addf(&remote, " %s",
- branch_get_color(BRANCH_COLOR_REMOTE));
-
-@@ builtin/branch.c: static char *build_format(struct ref_filter *filter, int maxwidth, const char *r -
- if (filter->verbose > 1)
- {
-- strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)",
-- branch_get_color(BRANCH_COLOR_WORKTREE), branch_get_color(BRANCH_COLOR_RESET));
-+ if (show_worktree)
-+ strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)",
-+ branch_get_color(BRANCH_COLOR_WORKTREE), branch_get_color(BRANCH_COLOR_RESET));
- strbuf_addf(&local, "%%(if)%%(upstream)%%(then)[%s%%(upstream:short)%s%%(if)%%(upstream:track)"
- "%%(then): %%(upstream:track,nobracket)%%(end)] %%(end)%%(contents:subject)",
- branch_get_color(BRANCH_COLOR_UPSTREAM), branch_get_color(BRANCH_COLOR_RESET));
-@@ builtin/branch.c: static char *build_format(struct ref_filter *filter, int maxwidth, const char *r
- return strbuf_detach(&fmt, NULL);
- }
-
-+static char *current_worktree_path(void)
-+{
-+ struct worktree **worktrees = get_worktrees(the_repository);
-+ char *path = NULL;
++currentworktree::
++ The absolute path to the current worktree, if the ref is checked
++ out there, in the same sense as for worktreepath. Empty string
++ otherwise, also when the ref is checked out only in other
++ worktrees. Use it with %(if) to treat the current worktree
++ differently from the others.
+
-+ for (size_t i = 0; worktrees[i]; i++) {
-+ if (worktrees[i]->is_current) {
-+ path = xstrdup(worktrees[i]->path);
-+ break;
-+ }
-+ }
-+ free_worktrees(worktrees);
-+ return path;
-+}
-+
-+/*
-+ * Is "refname" checked out in the worktree at "here", or is that
-+ * worktree rebasing or bisecting it?
-+ */
-+static int checked_out_here(const char *refname, const char *here)
-+{
-+ const char *path = branch_checked_out_worktree(refname);
-+
-+ return path && !strcmp(path, here);
-+}
-+
- static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sorting,
- struct ref_format *format, struct string_list *output)
- {
-@@ builtin/branch.c: static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sortin
- int maxwidth = 0;
- const char *remote_prefix = "";
- char *to_free = NULL;
-+ struct ref_format here_format = REF_FORMAT_INIT;
-+ char *here_to_free = NULL, *here = NULL;
-+ struct strbuf out = STRBUF_INIT, err = STRBUF_INIT;
-
- /*
- * If we are listing more than just remote branches,
-@@ builtin/branch.c: static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sortin
- if (filter->verbose)
- maxwidth = calc_maxwidth(&array, strlen(remote_prefix));
-
-- if (!format->format)
-- format->format = to_free = build_format(filter, maxwidth, remote_prefix);
-+ if (!format->format) {
-+ format->format = to_free = build_format(filter, maxwidth,
-+ remote_prefix, 1);
-+ here = current_worktree_path();
-+ here_format = *format;
-+ here_format.format = here_to_free = build_format(filter, maxwidth,
-+ remote_prefix, 0);
-+ }
- format->use_color = branch_use_color;
-+ here_format.use_color = branch_use_color;
-
-- if (verify_ref_format(format))
-+ if (verify_ref_format(format) ||
-+ (here && verify_ref_format(&here_format)))
- die(_("unable to parse format string"));
-
- filter_ahead_behind(the_repository, &array);
- ref_array_sort(sorting, &array);
-
-- if (column_active(colopts)) {
-- struct strbuf out = STRBUF_INIT, err = STRBUF_INIT;
--
-+ if (column_active(colopts))
- assert(!filter->verbose && "--column and --verbose are incompatible");
-
-- for (i = 0; i < array.nr; i++) {
-- strbuf_reset(&err);
-- strbuf_reset(&out);
-- if (format_ref_array_item(array.items[i], format, &out, &err))
-- die("%s", err.buf);
-+ for (i = 0; i < array.nr; i++) {
-+ struct ref_array_item *item = array.items[i];
-+ struct ref_format *f = format;
-
-+ if (here && checked_out_here(item->refname, here))
-+ f = &here_format;
-+
-+ strbuf_reset(&err);
-+ strbuf_reset(&out);
-+ if (format_ref_array_item(item, f, &out, &err))
-+ die("%s", err.buf);
-+
-+ if (column_active(colopts))
- /* format to a string_list to let print_columns() do its job */
- string_list_append(output, out.buf);
-+ else if (out.len || !format->array_opts.omit_empty) {
-+ fwrite(out.buf, 1, out.len, stdout);
-+ putchar('\n');
- }
--
-- strbuf_release(&err);
-- strbuf_release(&out);
-- } else {
-- print_formatted_ref_array(&array, format);
- }
-
-+ strbuf_release(&err);
-+ strbuf_release(&out);
- ref_array_clear(&array);
- free(to_free);
-+ free(here_to_free);
-+ free(here);
- }
-
- static void print_current_branch_name(void)
+ ahead-behind:<commit-ish>::
+ Two integers, separated by a space, demonstrating the number of
+ commits ahead and behind, respectively, when comparing the output

- ## t/t3203-branch-output.sh ##
-@@ t/t3203-branch-output.sh: test_expect_success 'branch being rebased in a worktree is marked' '
+ ## branch.c ##
+@@ branch.c: static int initialized_checked_out_branches;
+ static struct strmap current_checked_out_branches = STRMAP_INIT;
+ /* Like current_checked_out_branches, without the "update-ref" branches. */
+ static struct strmap checked_out_worktrees = STRMAP_INIT;
++/* The subset of checked_out_worktrees that the current worktree has. */
++static struct strmap current_worktree_branches = STRMAP_INIT;
+
+ enum branch_checkout_kind {
+ BRANCH_CHECKOUT_KIND_CHECKOUT,
+@@ branch.c: static struct checked_out_branch *checked_out_branches;
+ static size_t checked_out_branches_alloc, checked_out_branches_nr;
+
+ static void register_checked_out_branch(const char *prefix, const char *name,
+- const char *path,
++ const struct worktree *wt,
+ enum branch_checkout_kind kind)
+ {
+ char *refname = xstrfmt("%s%s", prefix, name);
+- char *path_copy = xstrdup(path);
++ char *path_copy = xstrdup(wt->path);
+
+ ALLOC_GROW(checked_out_branches, checked_out_branches_nr + 1,
+ checked_out_branches_alloc);
+@@ branch.c: static void register_checked_out_branch(const char *prefix, const char *name,
+ checked_out_branches_nr++;
+
+ strmap_put(&current_checked_out_branches, refname, path_copy);
+- if (kind != BRANCH_CHECKOUT_KIND_UPDATE_REF)
++ if (kind != BRANCH_CHECKOUT_KIND_UPDATE_REF) {
+ strmap_put(&checked_out_worktrees, refname, path_copy);
++ if (wt->is_current)
++ strmap_put(&current_worktree_branches, refname, path_copy);
++ }
+ }
+
+ static void prepare_checked_out_branches(void)
+@@ branch.c: static void prepare_checked_out_branches(void)
+ continue;
+
+ if (wt->head_ref) {
+- register_checked_out_branch("", wt->head_ref, wt->path,
++ register_checked_out_branch("", wt->head_ref, wt,
+ BRANCH_CHECKOUT_KIND_CHECKOUT);
+ }
+
+@@ branch.c: static void prepare_checked_out_branches(void)
+ (state.rebase_in_progress || state.rebase_interactive_in_progress) &&
+ state.branch) {
+ register_checked_out_branch("refs/heads/", state.branch,
+- wt->path,
++ wt,
+ BRANCH_CHECKOUT_KIND_REBASE);
+ }
+ wt_status_state_free_buffers(&state);
+@@ branch.c: static void prepare_checked_out_branches(void)
+ state.bisecting_from) {
+ register_checked_out_branch("refs/heads/",
+ state.bisecting_from,
+- wt->path,
++ wt,
+ BRANCH_CHECKOUT_KIND_BISECT);
+ }
+ wt_status_state_free_buffers(&state);
+@@ branch.c: static void prepare_checked_out_branches(void)
+ struct string_list_item *item;
+ for_each_string_list_item(item, &update_refs) {
+ register_checked_out_branch("", item->string,
+- wt->path,
++ wt,
+ BRANCH_CHECKOUT_KIND_UPDATE_REF);
+ }
+ string_list_clear(&update_refs, 1);
+@@ branch.c: const char *branch_checked_out_worktree(const char *refname)
+ return strmap_get(&checked_out_worktrees, refname);
+ }
+
++const char *branch_checked_out_current_worktree(const char *refname)
++{
++ prepare_checked_out_branches();
++ return strmap_get(&current_worktree_branches, refname);
++}
++
+ const char *branch_bisecting(const char *refname)
+ {
+ prepare_checked_out_branches();
+
+ ## branch.h ##
+@@ branch.h: const char *branch_checked_out(const char *refname);
+ */
+ const char *branch_checked_out_worktree(const char *refname);
+
++/*
++ * Like branch_checked_out_worktree(), but only for the current
++ * worktree: return its path if it has the branch 'refname' checked
++ * out, or is rebasing or bisecting it. Otherwise return NULL.
++ */
++const char *branch_checked_out_current_worktree(const char *refname);
++
+ /*
+ * If the branch at 'refname' is currently used for bisecting in a
+ * worktree, then return the path to that worktree.
+
+ ## ref-filter.c ##
+@@ ref-filter.c: enum atom_type {
+ ATOM_HEAD,
+ ATOM_COLOR,
+ ATOM_WORKTREEPATH,
++ ATOM_CURRENTWORKTREE,
+ ATOM_ALIGN,
+ ATOM_END,
+ ATOM_IF,
+@@ ref-filter.c: static struct {
+ [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
+ [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
+ [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
++ [ATOM_CURRENTWORKTREE] = { "currentworktree", SOURCE_NONE },
+ [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
+ [ATOM_END] = { "end", SOURCE_NONE },
+ [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
+@@ ref-filter.c: static int populate_value(struct ref_array_item *ref, struct strbuf *err)
+ v->s = xstrdup("");
+ continue;
+ }
++ else if (atom_type == ATOM_CURRENTWORKTREE) {
++ const char *path = NULL;
++
++ if (ref->kind == FILTER_REFS_BRANCHES)
++ path = branch_checked_out_current_worktree(ref->refname);
++ v->s = xstrdup(path ? path : "");
++ continue;
++ }
+ else if (atom_type == ATOM_SYMREF)
+ refname = get_symref(atom, ref);
+ else if (atom_type == ATOM_UPSTREAM) {
+
+ ## t/t6302-for-each-ref-filter.sh ##
+@@ t/t6302-for-each-ref-filter.sh: test_expect_success 'worktree atom ignores the HEAD of a bare repository' '
test_cmp expect actual
'

-+test_expect_success 'branch being rebased is not marked in its own worktree' '
-+ test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
-+ git worktree add -b rebasing rebase_dir branch-two &&
-+ (
-+ cd rebase_dir &&
-+ git commit --allow-empty -m rebase-me &&
-+ test_must_fail git rebase -f -x false HEAD~1 &&
-+ git branch --list rebasing >actual &&
-+ echo " rebasing" >expect &&
-+ test_cmp expect actual &&
-+ git branch -vv --list rebasing >actual &&
-+ test_grep ! "$(pwd)" actual &&
-+ git branch >actual &&
-+ test_grep "^\* (no branch, rebasing rebasing)" actual
-+ )
++test_expect_success 'currentworktree atom' '
++ test_when_finished "git -C current rebase --abort; rm -rf current; git worktree prune; git branch -D current" &&
++ git worktree add -b current current main &&
++ git -C current commit --allow-empty -m rebase-me &&
++ test_must_fail git -C current rebase -f -x false main &&
++ git for-each-ref --format="%(refname:short) [%(currentworktree)]" \
++ refs/heads/main refs/heads/current >actual &&
++ cat >expect <<-EOF &&
++ current []
++ main [$(pwd)]
++ EOF
++ test_cmp expect actual &&
++ git -C current for-each-ref --format="%(refname:short) [%(currentworktree)]" \
++ refs/heads/main refs/heads/current >actual &&
++ cat >expect <<-EOF &&
++ current [$(pwd)/current]
++ main []
++ EOF
++ test_cmp expect actual
+'
+
- test_expect_success 'branch being bisected in a worktree is marked' '
- test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
- git worktree add -b bisecting bisect_dir branch-two &&
-@@ t/t3203-branch-output.sh: test_expect_success 'branch being bisected in a worktree is marked' '
- git commit --allow-empty -m bisect-one &&
- git commit --allow-empty -m bisect-two &&
- git bisect start HEAD HEAD~2 &&
-- test_must_fail git symbolic-ref -q HEAD
-+ test_must_fail git symbolic-ref -q HEAD &&
-+ git branch --list bisecting >actual &&
-+ echo " bisecting" >expect &&
-+ test_cmp expect actual
- ) &&
- git branch --list bisecting >actual &&
- echo "+ bisecting" >expect &&
+ test_expect_success 'start after with empty value' '
+ cat >expect <<-\EOF &&
+ refs/heads/main
-: ---------- > 5: 4177c84d31 branch: do not mark the branch the current worktree is rebasing

Signature · 1 line
2.56.0
#40 lore raw

PATCH v5 1/5 worktree remove: refuse a worktree in the middle of an operation

"git worktree remove" refuses to remove a worktree with modified or untracked files unless --force is given, but it removes a worktree that is in the middle of a rebase, a "git am" session, a bisect, a cherry-pick or a revert when its files happen to be clean. The state of that operation lives in the worktree's own $GIT_DIR, so it is lost with the worktree. Examples of such a clean worktree are a rebase stopped at an "edit" or "break" line or after a failed "exec", a cherry-pick sequence after a conflict was resolved and committed, and a single cherry-pick or revert whose conflict was resolved to the current contents, which leaves CHERRY_PICK_HEAD or REVERT_HEAD behind.

Treat such a worktree as unclean: refuse to remove it unless --force is given, and name the operation in the message.

A worktree whose directory is already gone is still removed without --force, as before: the check is part of the check for a clean worktree, which is only done when the directory exists.

---
 Documentation/git-worktree.adoc | 17 ++++--
 builtin/worktree.c              | 37 ++++++++++++-
 t/t2403-worktree-move.sh        | 94 +++++++++++++++++++++++++++++++++
 3 files changed, 142 insertions(+), 6 deletions(-)
Documentation/git-worktree.adoc +12 -5
index e6e77252ab..cde17c9ab5 100644
@@ -141,10 +141,16 @@ the new working tree location.
 
 `remove`::
 
-Remove a worktree. Only clean worktrees (no untracked files and no
-modification in tracked files) can be removed. Unclean worktrees or ones
-with submodules can be removed with `--force`. The main worktree cannot be
-removed.
+Remove a worktree. The main worktree cannot be removed. Without
+`--force`, a worktree is not removed in these cases:
++
+--
+* The worktree has untracked files or modifications in tracked files.
+* The worktree has submodules.
+* The worktree is in the middle of a `git rebase`, `git am`,
+  `git bisect`, `git cherry-pick` or `git revert`. Removing the
+  worktree would lose the state of that operation.
+--
 
 `repair [<path>...]`::
 
@@ -189,7 +195,8 @@ twice. If the destination is already assigned to some other worktree but is
 missing (for instance, if _<new-path>_ was deleted manually), then `--force`
 allows the move to proceed; use `--force` twice if the destination is locked.
 +
-`remove` refuses to remove an unclean worktree unless `--force` is used.
+`remove` refuses to remove a worktree in the cases listed under
+`remove` above unless `--force` is used.
 To remove a locked worktree, specify `--force` twice.
 
 `-b <new-branch>`::
builtin/worktree.c +36 -1
index 77ecd0f71f..7f53215cda 100644
@@ -26,6 +26,7 @@
 #include "submodule.h"
 #include "utf8.h"
 #include "worktree.h"
+#include "wt-status.h"
 #include "quote.h"
 
 #define BUILTIN_WORKTREE_ADD_USAGE \
@@ -1408,6 +1409,38 @@ static void check_clean_worktree(struct worktree *wt,
 			  original_path, ret);
 }
 
+/*
+ * A rebase, "git am", bisect, cherry-pick or revert keeps its state in
+ * the worktree's own $GIT_DIR, and removing the worktree throws that
+ * away even when "git status" says the files are clean.
+ */
+static void check_no_operation_in_progress(struct worktree *wt,
+					   const char *original_path)
+{
+	struct wt_status_state state = { 0 };
+
+	if (wt_status_check_rebase(wt, &state)) {
+		if (state.am_in_progress)
+			die(_("'%s' is in the middle of an am session, use --force to delete it"),
+			    original_path);
+		die(_("'%s' is in the middle of a rebase, use --force to delete it"),
+		    original_path);
+	}
+	if (wt_status_check_bisect(wt, &state))
+		die(_("'%s' is in the middle of a bisect, use --force to delete it"),
+		    original_path);
+	wt_status_state_free_buffers(&state);
+	if (refs_ref_exists(get_worktree_ref_store(wt), "CHERRY_PICK_HEAD"))
+		die(_("'%s' is in the middle of a cherry-pick, use --force to delete it"),
+		    original_path);
+	if (refs_ref_exists(get_worktree_ref_store(wt), "REVERT_HEAD"))
+		die(_("'%s' is in the middle of a revert, use --force to delete it"),
+		    original_path);
+	if (is_directory(worktree_git_path(wt, "sequencer")))
+		die(_("'%s' is in the middle of a cherry-pick or revert, use --force to delete it"),
+		    original_path);
+}
+
 static int delete_git_work_tree(struct worktree *wt)
 {
 	struct strbuf sb = STRBUF_INIT;
@@ -1461,8 +1494,10 @@ static int remove_worktree(int ac, const char **av, const char *prefix,
 	strbuf_release(&errmsg);
 
 	if (file_exists(wt->path)) {
-		if (!force)
+		if (!force) {
+			check_no_operation_in_progress(wt, av[0]);
 			check_clean_worktree(wt, av[0]);
+		}
 
 		ret |= delete_git_work_tree(wt);
 	}
t/t2403-worktree-move.sh +94 -0

98 lines not on this page · raw message

Signature · 1 line
2.56.0
#41 lore raw

Re: [PATCH v5 1/5] worktree remove: refuse a worktree in the middle of an operation

builtin/worktree.c static void check_clean_worktree(struct worktree *wt, · line 1442

Quoted 11 lines · Jasper Mayone
builtin/worktree.c +10 -0
+static void check_no_operation_in_progress(struct worktree *wt,
+					   const char *original_path)
+{
+	struct wt_status_state state = { 0 };
+
+	if (wt_status_check_rebase(wt, &state)) {
...
+	if (is_directory(worktree_git_path(wt, "sequencer")))
+		die(_("'%s' is in the middle of a cherry-pick or revert, use --force to delete it"),
+		    original_path);
+}

Having a central place like this is a very good design to keep it extensible. In addition to "git worktree remove", we have protection against checking out the same branch in multiple worktrees. How should this check interact with the checks done in that other code path, if any?

builtin/worktree.c static int remove_worktree(int ac, const char **av, const char *prefix, · line 1500

Quoted 12 lines

static int delete_git_work_tree(struct worktree *wt) {

builtin/worktree.c +3 -1
 	struct strbuf sb = STRBUF_INIT;
@@ -1461,8 +1494,10 @@ static int remove_worktree(int ac, const char **av, const char *prefix,
 	strbuf_release(&errmsg);
 
 	if (file_exists(wt->path)) {
-		if (!force)
+		if (!force) {
+			check_no_operation_in_progress(wt, av[0]);
 			check_clean_worktree(wt, av[0]);
+		}

In the longer term, I think it would make sense to create a single helper function that checks if the worktree is in discardable state (without dying. Just return an error code instead), call it from here, and have call(s) to die() here. Then move everything below the callchain to worktree.c one level up to libify.

Not in a scope for this change, of course. #leftoverbits.

#42 lore raw

Re: [PATCH v5 1/5] worktree remove: refuse a worktree in the middle of an operation

Quoted 5 lines · Junio C Hamano

Having a central place like this is a very good design to keep it extensible. In addition to "git worktree remove", we have protection against checking out the same branch in multiple worktrees. How should this check interact with the checks done in that other code path, if any?

The two checks answer different questions, and I think they should stay separate.

die_if_checked_out() asks "does another worktree hold this branch?". It goes through is_shared_symref(), which uses is_worktree_being_rebased() and is_worktree_being_bisected(), so it only cares about a rebase or bisect that names a branch.

check_no_operation_in_progress() asks "would removing this worktree lose state?". That is also true for a rebase of a detached HEAD, for "git am", and for a cherry-pick or revert, which hold no branch.

They agree where they meet: while a worktree is rebasing "topic", "git worktree remove" refuses it and "git checkout topic" elsewhere refuses too. After "git worktree remove --force", the worktree is gone, so the branch is free again.

You asked the same thing on [3/5], so I answer it here too. The detection overlaps, but the result does not. There are now three places that read the rebase and bisect state of a worktree:
prepare_checked_out_branches() in branch.c, the two is_worktree_being_*() helpers in worktree.c, and this function. prepare_checked_out_branches() records only branch names, so 1/5 cannot use it as it is: it would miss a detached rebase and "git am".

A helper in worktree.c that reports which operation a worktree is in, and on which branch if any, could serve all three. That fits well with the libification you describe below:

Quoted 7 lines

In the longer term, I think it would make sense to create a single helper function that checks if the worktree is in discardable state (without dying. Just return an error code instead), call it from here, and have call(s) to die() here. Then move everything below the callchain to worktree.c one level up to libify.

Not in a scope for this change, of course. #leftoverbits.

so I would prefer to do it as a separate series on top of this one, if that is OK with you.

Thanks
Jasper

#43 lore raw

PATCH v5 2/5 doc: for-each-ref: say how to read %(worktreepath) safely

In reply to Jasper Mayone

The path that %(worktreepath) gives can contain a newline, which breaks a script that reads one record per line. Say how to avoid
that: use a quoting option, or end the atom with %00 and look for the NUL before the LF that ends the record.

Also say that only one worktree is shown when a branch is checked out in more than one worktree.

---
 Documentation/git-for-each-ref.adoc | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
Documentation/git-for-each-ref.adoc +6 -1
index a7b31e8aaf..9247737aa7 100644
@@ -183,7 +183,12 @@ but if used together the last option is selected.
 `worktreepath`::
 	The absolute path to the worktree in which the ref is checked
 	out, if it is checked out in any linked worktree. Empty string
-	otherwise.
+	otherwise. If the ref is checked out in more than one worktree,
+	only one of them is shown. The path can contain a newline, so
+	use one of the quoting options such as `--shell`, or follow
+	`%(worktreepath)` with `%00` and parse the output by looking for
+	the `NUL` after the path and then for the `LF` that ends each
+	record.
 
 `ahead-behind:<commit-ish>`::
 	Two integers, separated by a space, demonstrating the number of
Signature · 1 line
2.56.0
#44 lore raw

Re: [PATCH v5 2/5] doc: for-each-ref: say how to read %(worktreepath) safely

Quoted 4 lines · Jasper Mayone

The path that %(worktreepath) gives can contain a newline, which breaks a script that reads one record per line. Say how to avoid
that: use a quoting option, or end the atom with %00 and look for the NUL before the LF that ends the record.

Is this the only item that can emit an arbitrary sequence of bytes (other than NUL in the middle)? %(contents:body) can have multiple lines for obvious reasons but we do not talk about quoting at all.

I am not saying I do not want to see this added. I am wondering if there is a more central place we can describe the choices fully (including "use --shell or %00") and sprinkle short pointers from %(worktreepath) and other places.

Quoted 2 lines

Also say that only one worktree is shown when a branch is checked out in more than one worktree.

OK. When a user wants to clean it up, for-each-ref would not be the tool to use ("git worktree list" is), so this may be good enough. If somebody has specific needs, they can add %(worktreepath:all) or something to fill the gap.

Assuming that we will leave the "shouldn't we have a single quoting help that is referred to from places?" question out, this step looks good to me.

Quoted 9 lines
Documentation/git-for-each-ref.adoc +6 -0
+	otherwise. If the ref is checked out in more than one worktree,
+	only one of them is shown. The path can contain a newline, so
+	use one of the quoting options such as `--shell`, or follow
+	`%(worktreepath)` with `%00` and parse the output by looking for
+	the `NUL` after the path and then for the `LF` that ends each
+	record.
 
 `ahead-behind:<commit-ish>`::
 	Two integers, separated by a space, demonstrating the number of
#45 lore raw

PATCH v5 3/5 ref-filter: name the worktree of a branch being rebased or bisected

In reply to Jasper Mayone

%(worktreepath) gives the worktree that has a branch checked out, and "git branch" uses it to mark such branches with "+". It only looks at the HEAD of each worktree, so while a worktree is rebasing or bisecting a branch, its HEAD is detached and the branch shows no worktree at all.

The rest of Git already treats that branch as checked out: "git worktree add" and "git branch -d" refuse it, because finishing the rebase or bisect will check it out again. But no command shows which worktree is working on the branch: "git worktree list" shows such a worktree as "(detached HEAD)", and %(worktreepath) is empty.

branch.c already knows the answer, as prepare_checked_out_branches() records the branch that each worktree has checked out, is rebasing or is bisecting. Record those branches in a map as well, add branch_checked_out_worktree() to look a branch up in it, and use that for %(worktreepath) in place of the map that ref-filter.c builds from the HEAD of each worktree.

The new function skips the branches that "rebase --update-refs" will update. branch_checked_out() includes them, so that they cannot be checked out or deleted during the rebase, but the worktree that runs the rebase has not checked them out. %(worktreepath) therefore stays empty for them, unlike branch_checked_out().

This also changes the result for a bare repository: its HEAD names a branch, and %(worktreepath) used to give the path of the bare repository for that branch. "git branch" in a linked worktree marked the branch with "+", although no worktree has it checked out and "git worktree add" lets you check it out. prepare_checked_out_branches() skips bare repositories, so %(worktreepath) is now empty for that branch and "git branch" no longer marks it.

---
 Documentation/git-branch.adoc       |  6 ++-
 Documentation/git-for-each-ref.adoc |  5 +-
 branch.c                            | 10 ++++
 branch.h                            |  9 ++++
 ref-filter.c                        | 74 ++--------------------------
 t/t3203-branch-output.sh            | 29 +++++++++++
 t/t6302-for-each-ref-filter.sh      | 76 +++++++++++++++++++++++++++++
 7 files changed, 135 insertions(+), 74 deletions(-)
Documentation/git-branch.adoc +4 -2
index bfdf459329..510b0afc74 100644
@@ -33,8 +33,10 @@ DESCRIPTION
 If `--list` is given, or if there are no non-option arguments, existing
 branches are listed; the current branch will be highlighted in green and
 marked with an asterisk.  Any branches checked out in linked worktrees will
-be highlighted in cyan and marked with a plus sign. Option `-r` causes the
-remote-tracking branches to be listed,
+be highlighted in cyan and marked with a plus sign. A branch that a
+worktree is rebasing or bisecting counts as checked out in that
+worktree, so the other worktrees mark it in the same way. Option `-r`
+causes the remote-tracking branches to be listed,
 and option `-a` shows both local and remote branches.
 
 If a `<pattern>`
Documentation/git-for-each-ref.adoc +4 -1
index 9247737aa7..4456b4809a 100644
@@ -182,7 +182,10 @@ but if used together the last option is selected.
 
 `worktreepath`::
 	The absolute path to the worktree in which the ref is checked
-	out, if it is checked out in any linked worktree. Empty string
+	out, if it is checked out in any linked worktree. A branch that
+	a worktree is rebasing or bisecting counts as checked out there,
+	although that worktree's `HEAD` is detached. A branch that
+	`git rebase --update-refs` will update does not. Empty string
 	otherwise. If the ref is checked out in more than one worktree,
 	only one of them is shown. The path can contain a newline, so
 	use one of the quoting options such as `--shell`, or follow
branch.c +10 -0
index 5bb1c28915..87f3ffc35f 100644
@@ -384,6 +384,8 @@ int validate_branchname(const char *name, struct strbuf *ref)
 
 static int initialized_checked_out_branches;
 static struct strmap current_checked_out_branches = STRMAP_INIT;
+/* Like current_checked_out_branches, without the "update-ref" branches. */
+static struct strmap checked_out_worktrees = STRMAP_INIT;
 
 enum branch_checkout_kind {
 	BRANCH_CHECKOUT_KIND_CHECKOUT,
@@ -416,6 +418,8 @@ static void register_checked_out_branch(const char *prefix, const char *name,
 	checked_out_branches_nr++;
 
 	strmap_put(&current_checked_out_branches, refname, path_copy);
+	if (kind != BRANCH_CHECKOUT_KIND_UPDATE_REF)
+		strmap_put(&checked_out_worktrees, refname, path_copy);
 }
 
 static void prepare_checked_out_branches(void)
@@ -485,6 +489,12 @@ const char *branch_checked_out(const char *refname)
 	return strmap_get(&current_checked_out_branches, refname);
 }
 
+const char *branch_checked_out_worktree(const char *refname)
+{
+	prepare_checked_out_branches();
+	return strmap_get(&checked_out_worktrees, refname);
+}
+
 const char *branch_bisecting(const char *refname)
 {
 	prepare_checked_out_branches();
branch.h +9 -0
index 95b2431f24..60cb92a3e4 100644
@@ -106,6 +106,15 @@ void create_branches_recursively(struct repository *r, const char *name,
  */
 const char *branch_checked_out(const char *refname);
 
+/*
+ * If a worktree has the branch 'refname' checked out, or is rebasing or
+ * bisecting it, return the path of that worktree, or of the last one if
+ * there are more. Otherwise return NULL. Unlike branch_checked_out(),
+ * this ignores the branches that "git rebase --update-refs" will
+ * update, because no worktree has them checked out.
+ */
+const char *branch_checked_out_worktree(const char *refname);
+
 /*
  * If the branch at 'refname' is currently used for bisecting in a
  * worktree, then return the path to that worktree.
ref-filter.c +3 -71

101 lines not on this page · raw message

t/t3203-branch-output.sh +29 -0
index 7c44186341..debfac5f26 100755
@@ -442,6 +442,35 @@ test_expect_success 'worktree colors correct' '
 	test_cmp expect actual
 '
 
+test_expect_success 'branch being rebased in a worktree is marked' '
+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebase_dir branch-two &&
+	(
+		cd rebase_dir &&
+		git commit --allow-empty -m rebase-me &&
+		test_must_fail git rebase -f -x false HEAD~1 &&
+		test_must_fail git symbolic-ref -q HEAD
+	) &&
+	git branch --list rebasing >actual &&
+	echo "+ rebasing" >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success 'branch being bisected in a worktree is marked' '
+	test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
+	git worktree add -b bisecting bisect_dir branch-two &&
+	(
+		cd bisect_dir &&
+		git commit --allow-empty -m bisect-one &&
+		git commit --allow-empty -m bisect-two &&
+		git bisect start HEAD HEAD~2 &&
+		test_must_fail git symbolic-ref -q HEAD
+	) &&
+	git branch --list bisecting >actual &&
+	echo "+ bisecting" >expect &&
+	test_cmp expect actual
+'
+
 test_expect_success "set up color tests" '
 	echo "<RED>main<RESET>" >expect.color &&
 	echo "main" >expect.bare &&
t/t6302-for-each-ref-filter.sh +76 -0

88 lines not on this page · raw message

Signature · 1 line
2.56.0
#46 lore raw

Re: [PATCH v5 3/5] ref-filter: name the worktree of a branch being rebased or bisected

Quoted 7 lines · Jasper Mayone

branch.c already knows the answer, as prepare_checked_out_branches() records the branch that each worktree has checked out, is rebasing or is bisecting. Record those branches in a map as well, add branch_checked_out_worktree() to look a branch up in it, and use that for %(worktreepath) in place of the map that ref-filter.c builds from the HEAD of each worktree.
..

Quoted 5 lines
 Documentation/git-branch.adoc       |  6 ++-
 Documentation/git-for-each-ref.adoc |  5 +-
 branch.c                            | 10 ++++
 branch.h                            |  9 ++++
 ref-filter.c                        | 74 ++--------------------------

Nice loss of duplicated logic.

branch.c const char *branch_checked_out(const char *refname) · line 496

Quoted 5 lines
branch.c +5 -0
+const char *branch_checked_out_worktree(const char *refname)
+{
+	prepare_checked_out_branches();
+	return strmap_get(&checked_out_worktrees, refname);
+}

Yes, this is related to what I asked while reading [1/5]. Doesn't what the prepare_checked_out_branches() function in branch.c knows overlap with the new function added there, and shouldn't we look into reusing it in the new code path if it is the case?

#47 lore raw

PATCH v5 4/5 ref-filter: add %(currentworktree)

In reply to Jasper Mayone

%(worktreepath) names the worktree that has a branch checked out, or is rebasing or bisecting it, but a format cannot tell if that worktree is the current one. Comparing %(worktreepath) with a fixed path in %(if:equals=...) does not work for every path, because a ")" ends the atom.

Add %(currentworktree), which gives the path of the current worktree when that worktree has the branch, and an empty string otherwise. branch.c records these branches when it reads the worktrees, in a second map next to the one that %(worktreepath) uses, so the lookup is one map lookup per ref.

The next commit uses it in "git branch".

---
 Documentation/git-for-each-ref.adoc |  7 +++++++
 branch.c                            | 25 ++++++++++++++++++-------
 branch.h                            |  7 +++++++
 ref-filter.c                        | 10 ++++++++++
 t/t6302-for-each-ref-filter.sh      | 21 +++++++++++++++++++++
 5 files changed, 63 insertions(+), 7 deletions(-)
Documentation/git-for-each-ref.adoc +7 -0
index 4456b4809a..5e2da92ee2 100644
@@ -193,6 +193,13 @@ but if used together the last option is selected.
 	the `NUL` after the path and then for the `LF` that ends each
 	record.
 
+`currentworktree`::
+	The absolute path to the current worktree, if the ref is checked
+	out there, in the same sense as for `worktreepath`. Empty string
+	otherwise, also when the ref is checked out only in other
+	worktrees. Use it with `%(if)` to treat the current worktree
+	differently from the others.
+
 `ahead-behind:<commit-ish>`::
 	Two integers, separated by a space, demonstrating the number of
 	commits ahead and behind, respectively, when comparing the output
branch.c +18 -7
index 87f3ffc35f..4de789b7ae 100644
@@ -386,6 +386,8 @@ static int initialized_checked_out_branches;
 static struct strmap current_checked_out_branches = STRMAP_INIT;
 /* Like current_checked_out_branches, without the "update-ref" branches. */
 static struct strmap checked_out_worktrees = STRMAP_INIT;
+/* The subset of checked_out_worktrees that the current worktree has. */
+static struct strmap current_worktree_branches = STRMAP_INIT;
 
 enum branch_checkout_kind {
 	BRANCH_CHECKOUT_KIND_CHECKOUT,
@@ -404,11 +406,11 @@ static struct checked_out_branch *checked_out_branches;
 static size_t checked_out_branches_alloc, checked_out_branches_nr;
 
 static void register_checked_out_branch(const char *prefix, const char *name,
-					const char *path,
+					const struct worktree *wt,
 					enum branch_checkout_kind kind)
 {
 	char *refname = xstrfmt("%s%s", prefix, name);
-	char *path_copy = xstrdup(path);
+	char *path_copy = xstrdup(wt->path);
 
 	ALLOC_GROW(checked_out_branches, checked_out_branches_nr + 1,
 		   checked_out_branches_alloc);
@@ -418,8 +420,11 @@ static void register_checked_out_branch(const char *prefix, const char *name,
 	checked_out_branches_nr++;
 
 	strmap_put(&current_checked_out_branches, refname, path_copy);
-	if (kind != BRANCH_CHECKOUT_KIND_UPDATE_REF)
+	if (kind != BRANCH_CHECKOUT_KIND_UPDATE_REF) {
 		strmap_put(&checked_out_worktrees, refname, path_copy);
+		if (wt->is_current)
+			strmap_put(&current_worktree_branches, refname, path_copy);
+	}
 }
 
 static void prepare_checked_out_branches(void)
@@ -443,7 +448,7 @@ static void prepare_checked_out_branches(void)
 			continue;
 
 		if (wt->head_ref) {
-			register_checked_out_branch("", wt->head_ref, wt->path,
+			register_checked_out_branch("", wt->head_ref, wt,
 						    BRANCH_CHECKOUT_KIND_CHECKOUT);
 		}
 
@@ -451,7 +456,7 @@ static void prepare_checked_out_branches(void)
 		    (state.rebase_in_progress || state.rebase_interactive_in_progress) &&
 		    state.branch) {
 			register_checked_out_branch("refs/heads/", state.branch,
-						    wt->path,
+						    wt,
 						    BRANCH_CHECKOUT_KIND_REBASE);
 		}
 		wt_status_state_free_buffers(&state);
@@ -460,7 +465,7 @@ static void prepare_checked_out_branches(void)
 		    state.bisecting_from) {
 			register_checked_out_branch("refs/heads/",
 						    state.bisecting_from,
-						    wt->path,
+						    wt,
 						    BRANCH_CHECKOUT_KIND_BISECT);
 		}
 		wt_status_state_free_buffers(&state);
@@ -471,7 +476,7 @@ static void prepare_checked_out_branches(void)
 			struct string_list_item *item;
 			for_each_string_list_item(item, &update_refs) {
 				register_checked_out_branch("", item->string,
-							    wt->path,
+							    wt,
 							    BRANCH_CHECKOUT_KIND_UPDATE_REF);
 			}
 			string_list_clear(&update_refs, 1);
@@ -495,6 +500,12 @@ const char *branch_checked_out_worktree(const char *refname)
 	return strmap_get(&checked_out_worktrees, refname);
 }
 
+const char *branch_checked_out_current_worktree(const char *refname)
+{
+	prepare_checked_out_branches();
+	return strmap_get(&current_worktree_branches, refname);
+}
+
 const char *branch_bisecting(const char *refname)
 {
 	prepare_checked_out_branches();
branch.h +7 -0
index 60cb92a3e4..744e1eec1d 100644
@@ -115,6 +115,13 @@ const char *branch_checked_out(const char *refname);
  */
 const char *branch_checked_out_worktree(const char *refname);
 
+/*
+ * Like branch_checked_out_worktree(), but only for the current
+ * worktree: return its path if it has the branch 'refname' checked
+ * out, or is rebasing or bisecting it. Otherwise return NULL.
+ */
+const char *branch_checked_out_current_worktree(const char *refname);
+
 /*
  * If the branch at 'refname' is currently used for bisecting in a
  * worktree, then return the path to that worktree.
ref-filter.c +10 -0
index b636e56199..498d09da8f 100644
@@ -142,6 +142,7 @@ enum atom_type {
 	ATOM_HEAD,
 	ATOM_COLOR,
 	ATOM_WORKTREEPATH,
+	ATOM_CURRENTWORKTREE,
 	ATOM_ALIGN,
 	ATOM_END,
 	ATOM_IF,
@@ -960,6 +961,7 @@ static struct {
 	[ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
 	[ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
 	[ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
+	[ATOM_CURRENTWORKTREE] = { "currentworktree", SOURCE_NONE },
 	[ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
 	[ATOM_END] = { "end", SOURCE_NONE },
 	[ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
@@ -2420,6 +2422,14 @@ static int populate_value(struct ref_array_item *ref, struct strbuf *err)
 				v->s = xstrdup("");
 			continue;
 		}
+		else if (atom_type == ATOM_CURRENTWORKTREE) {
+			const char *path = NULL;
+
+			if (ref->kind == FILTER_REFS_BRANCHES)
+				path = branch_checked_out_current_worktree(ref->refname);
+			v->s = xstrdup(path ? path : "");
+			continue;
+		}
 		else if (atom_type == ATOM_SYMREF)
 			refname = get_symref(atom, ref);
 		else if (atom_type == ATOM_UPSTREAM) {
t/t6302-for-each-ref-filter.sh +21 -0
index 317ed6f6cd..32522f1ff3 100755
@@ -617,6 +617,27 @@ test_expect_success 'worktree atom ignores the HEAD of a bare repository' '
 	test_cmp expect actual
 '
 
+test_expect_success 'currentworktree atom' '
+	test_when_finished "git -C current rebase --abort; rm -rf current; git worktree prune; git branch -D current" &&
+	git worktree add -b current current main &&
+	git -C current commit --allow-empty -m rebase-me &&
+	test_must_fail git -C current rebase -f -x false main &&
+	git for-each-ref --format="%(refname:short) [%(currentworktree)]" \
+		refs/heads/main refs/heads/current >actual &&
+	cat >expect <<-EOF &&
+	current []
+	main [$(pwd)]
+	EOF
+	test_cmp expect actual &&
+	git -C current for-each-ref --format="%(refname:short) [%(currentworktree)]" \
+		refs/heads/main refs/heads/current >actual &&
+	cat >expect <<-EOF &&
+	current [$(pwd)/current]
+	main []
+	EOF
+	test_cmp expect actual
+'
+
 test_expect_success 'start after with empty value' '
 	cat >expect <<-\EOF &&
 	refs/heads/main
Signature · 1 line
2.56.0
#48 lore raw

Re: [PATCH v5 4/5] ref-filter: add %(currentworktree)

Quoted 8 lines · Jasper Mayone

%(worktreepath) names the worktree that has a branch checked out, or is rebasing or bisecting it, but a format cannot tell if that worktree is the current one. Comparing %(worktreepath) with a fixed path in %(if:equals=...) does not work for every path, because a ")" ends the atom.

Add %(currentworktree), which gives the path of the current worktree when that worktree has the branch, and an empty string otherwise.

"has the branch checked out"?

Quoted 3 lines

branch.c records these branches when it reads the worktrees, in a second map next to the one that %(worktreepath) uses, so the lookup is one map lookup per ref.

#49 lore raw

Re: [PATCH v5 4/5] ref-filter: add %(currentworktree)

In reply to Jasper Mayone

Hi Jasper

Quoted 11 lines · Jasper Mayone

%(worktreepath) names the worktree that has a branch checked out, or is rebasing or bisecting it, but a format cannot tell if that worktree is the current one. Comparing %(worktreepath) with a fixed path in %(if:equals=...) does not work for every path, because a ")" ends the atom.

Add %(currentworktree), which gives the path of the current worktree when that worktree has the branch, and an empty string otherwise. branch.c records these branches when it reads the worktrees, in a second map next to the one that %(worktreepath) uses, so the lookup is one map lookup per ref.

When I suggested %(currentworktree) I was imagining it would be a boolean format like %(HEAD) (i.e. it would print '*' if the ref was checked out in the current worktree). If we want to print the path instead, we should call it %(currentworktreepath) to match %(worktreepath). However, I'm not sure there is much value in printing the path, as that can be obtained with %(worktreepath).

While writing this email, I've just realized that %(HEAD) effectively tells us if we're in the current worktree, so another approach would be to extend that to handle branches that are being rebased or bisected, rather than adding a new format specifier. I haven't thought about it enough to have an opinion on whether that is a good idea.

A couple of thoughts on the implementation

1 - if a branch is checked out in two different worktrees it would be
helpful if %(currentworktree) and %(worktreepath) agreed on which worktree to report. In practice that would mean %(worktreepath) always reporting the path of the current worktree if the branch is checked out there. With the implementation here, it is possible for them to report different worktrees.

2 - why are we using a hashmap to store a single entry? It would be more
efficient to simply record the refname and path in separate strings and use strcmp(refname, current_worktree_branch) to determine whether refname is checked out in the current worktree. If we change to a boolean format we don't even need to record the worktree path.

Thanks

Phillip

Quoted 204 lines

The next commit uses it in "git branch".

---
  Documentation/git-for-each-ref.adoc |  7 +++++++
  branch.c                            | 25 ++++++++++++++++++-------
  branch.h                            |  7 +++++++
  ref-filter.c                        | 10 ++++++++++
  t/t6302-for-each-ref-filter.sh      | 21 +++++++++++++++++++++
  5 files changed, 63 insertions(+), 7 deletions(-)
Documentation/git-for-each-ref.adoc +7 -0
index 4456b4809a..5e2da92ee2 100644
@@ -193,6 +193,13 @@ but if used together the last option is selected.
  	the `NUL` after the path and then for the `LF` that ends each
  	record.
 
+`currentworktree`::
+	The absolute path to the current worktree, if the ref is checked
+	out there, in the same sense as for `worktreepath`. Empty string
+	otherwise, also when the ref is checked out only in other
+	worktrees. Use it with `%(if)` to treat the current worktree
+	differently from the others.
+
  `ahead-behind:<commit-ish>`::
  	Two integers, separated by a space, demonstrating the number of
  	commits ahead and behind, respectively, when comparing the output
branch.c +18 -7
index 87f3ffc35f..4de789b7ae 100644
@@ -386,6 +386,8 @@ static int initialized_checked_out_branches;
  static struct strmap current_checked_out_branches = STRMAP_INIT;
  /* Like current_checked_out_branches, without the "update-ref" branches. */
  static struct strmap checked_out_worktrees = STRMAP_INIT;
+/* The subset of checked_out_worktrees that the current worktree has. */
+static struct strmap current_worktree_branches = STRMAP_INIT;
 
  enum branch_checkout_kind {
  	BRANCH_CHECKOUT_KIND_CHECKOUT,
@@ -404,11 +406,11 @@ static struct checked_out_branch *checked_out_branches;
  static size_t checked_out_branches_alloc, checked_out_branches_nr;
 
  static void register_checked_out_branch(const char *prefix, const char *name,
-					const char *path,
+					const struct worktree *wt,
  					enum branch_checkout_kind kind)
  {
  	char *refname = xstrfmt("%s%s", prefix, name);
-	char *path_copy = xstrdup(path);
+	char *path_copy = xstrdup(wt->path);
 
  	ALLOC_GROW(checked_out_branches, checked_out_branches_nr + 1,
  		   checked_out_branches_alloc);
@@ -418,8 +420,11 @@ static void register_checked_out_branch(const char *prefix, const char *name,
  	checked_out_branches_nr++;
 
  	strmap_put(&current_checked_out_branches, refname, path_copy);
-	if (kind != BRANCH_CHECKOUT_KIND_UPDATE_REF)
+	if (kind != BRANCH_CHECKOUT_KIND_UPDATE_REF) {
  		strmap_put(&checked_out_worktrees, refname, path_copy);
+		if (wt->is_current)
+			strmap_put(&current_worktree_branches, refname, path_copy);
+	}
  }
 
  static void prepare_checked_out_branches(void)
@@ -443,7 +448,7 @@ static void prepare_checked_out_branches(void)
  			continue;
 
  		if (wt->head_ref) {
-			register_checked_out_branch("", wt->head_ref, wt->path,
+			register_checked_out_branch("", wt->head_ref, wt,
  						    BRANCH_CHECKOUT_KIND_CHECKOUT);
  		}
 
@@ -451,7 +456,7 @@ static void prepare_checked_out_branches(void)
  		    (state.rebase_in_progress || state.rebase_interactive_in_progress) &&
  		    state.branch) {
  			register_checked_out_branch("refs/heads/", state.branch,
-						    wt->path,
+						    wt,
  						    BRANCH_CHECKOUT_KIND_REBASE);
  		}
  		wt_status_state_free_buffers(&state);
@@ -460,7 +465,7 @@ static void prepare_checked_out_branches(void)
  		    state.bisecting_from) {
  			register_checked_out_branch("refs/heads/",
  						    state.bisecting_from,
-						    wt->path,
+						    wt,
  						    BRANCH_CHECKOUT_KIND_BISECT);
  		}
  		wt_status_state_free_buffers(&state);
@@ -471,7 +476,7 @@ static void prepare_checked_out_branches(void)
  			struct string_list_item *item;
  			for_each_string_list_item(item, &update_refs) {
  				register_checked_out_branch("", item->string,
-							    wt->path,
+							    wt,
  							    BRANCH_CHECKOUT_KIND_UPDATE_REF);
  			}
  			string_list_clear(&update_refs, 1);
@@ -495,6 +500,12 @@ const char *branch_checked_out_worktree(const char *refname)
  	return strmap_get(&checked_out_worktrees, refname);
  }
 
+const char *branch_checked_out_current_worktree(const char *refname)
+{
+	prepare_checked_out_branches();
+	return strmap_get(&current_worktree_branches, refname);
+}
+
  const char *branch_bisecting(const char *refname)
  {
  	prepare_checked_out_branches();
branch.h +7 -0
index 60cb92a3e4..744e1eec1d 100644
@@ -115,6 +115,13 @@ const char *branch_checked_out(const char *refname);
   */
  const char *branch_checked_out_worktree(const char *refname);
 
+/*
+ * Like branch_checked_out_worktree(), but only for the current
+ * worktree: return its path if it has the branch 'refname' checked
+ * out, or is rebasing or bisecting it. Otherwise return NULL.
+ */
+const char *branch_checked_out_current_worktree(const char *refname);
+
  /*
   * If the branch at 'refname' is currently used for bisecting in a
   * worktree, then return the path to that worktree.
ref-filter.c +10 -0
index b636e56199..498d09da8f 100644
@@ -142,6 +142,7 @@ enum atom_type {
  	ATOM_HEAD,
  	ATOM_COLOR,
  	ATOM_WORKTREEPATH,
+	ATOM_CURRENTWORKTREE,
  	ATOM_ALIGN,
  	ATOM_END,
  	ATOM_IF,
@@ -960,6 +961,7 @@ static struct {
  	[ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
  	[ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
  	[ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
+	[ATOM_CURRENTWORKTREE] = { "currentworktree", SOURCE_NONE },
  	[ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
  	[ATOM_END] = { "end", SOURCE_NONE },
  	[ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
@@ -2420,6 +2422,14 @@ static int populate_value(struct ref_array_item *ref, struct strbuf *err)
  				v->s = xstrdup("");
  			continue;
  		}
+		else if (atom_type == ATOM_CURRENTWORKTREE) {
+			const char *path = NULL;
+
+			if (ref->kind == FILTER_REFS_BRANCHES)
+				path = branch_checked_out_current_worktree(ref->refname);
+			v->s = xstrdup(path ? path : "");
+			continue;
+		}
  		else if (atom_type == ATOM_SYMREF)
  			refname = get_symref(atom, ref);
  		else if (atom_type == ATOM_UPSTREAM) {
t/t6302-for-each-ref-filter.sh +21 -0
index 317ed6f6cd..32522f1ff3 100755
@@ -617,6 +617,27 @@ test_expect_success 'worktree atom ignores the HEAD of a bare repository' '
  	test_cmp expect actual
  '
 
+test_expect_success 'currentworktree atom' '
+	test_when_finished "git -C current rebase --abort; rm -rf current; git worktree prune; git branch -D current" &&
+	git worktree add -b current current main &&
+	git -C current commit --allow-empty -m rebase-me &&
+	test_must_fail git -C current rebase -f -x false main &&
+	git for-each-ref --format="%(refname:short) [%(currentworktree)]" \
+		refs/heads/main refs/heads/current >actual &&
+	cat >expect <<-EOF &&
+	current []
+	main [$(pwd)]
+	EOF
+	test_cmp expect actual &&
+	git -C current for-each-ref --format="%(refname:short) [%(currentworktree)]" \
+		refs/heads/main refs/heads/current >actual &&
+	cat >expect <<-EOF &&
+	current [$(pwd)/current]
+	main []
+	EOF
+	test_cmp expect actual
+'
+
  test_expect_success 'start after with empty value' '
  	cat >expect <<-\EOF &&
  	refs/heads/main
#50 lore raw

Re: [PATCH v5 4/5] ref-filter: add %(currentworktree)

Hi Phillip

Quoted 3 lines · Phillip Wood

When I suggested %(currentworktree) I was imagining it would be a boolean format like %(HEAD) (i.e. it would print '*' if the ref was checked out in the current worktree).

Thank you for the review. Our emails crossed: Junio was against 5/5, because in a long branch list he wants the "+" next to the branch that his own worktree is bisecting, and I agreed to stop the series at 3/5 [1]. 4/5 existed only for 5/5, so it is dropped too.

Your idea to extend %(HEAD) to branches that are being rebased or bisected is interesting. I will keep it, and your two points on the implementation, in mind if I come back to this later.

[1] https://lore.kernel.org/git/[email protected]/

Thanks
Jasper

#51 lore raw

PATCH v5 5/5 branch: do not mark the branch the current worktree is rebasing

In reply to Jasper Mayone

Since "ref-filter: name the worktree of a branch being rebased or bisected", "git branch" marks a branch with "+" when a worktree is rebasing or bisecting it. In that worktree itself, the list already starts with "* (no branch, rebasing topic)", so a "+ topic" line below it shows the same branch twice.

Use %(currentworktree) in the default format, so that a branch that the current worktree has gets no "+" mark and no "(path)" with -vv. A branch that is checked out normally in the current worktree is not affected, as %(HEAD) already marks it with "*" before these checks.

---
 builtin/branch.c         | 10 ++++++++--
 t/t3203-branch-output.sh | 22 +++++++++++++++++++++-
 2 files changed, 29 insertions(+), 3 deletions(-)
builtin/branch.c +8 -2
index a613148fc7..87670d16e4 100644
@@ -424,8 +424,14 @@ static char *build_format(struct ref_filter *filter, int maxwidth, const char *r
 	struct strbuf local = STRBUF_INIT;
 	struct strbuf remote = STRBUF_INIT;
 
-	strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else)  %s%%(end)%%(end)",
+	/*
+	 * Mark a branch that another worktree has checked out with "+".
+	 * A branch that the current worktree is rebasing or bisecting has
+	 * no mark, as the "(no branch, ...)" line already shows its name.
+	 */
+	strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(currentworktree)%%(then)  %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else)  %s%%(end)%%(end)%%(end)",
 			branch_get_color(BRANCH_COLOR_CURRENT),
+			branch_get_color(BRANCH_COLOR_LOCAL),
 			branch_get_color(BRANCH_COLOR_WORKTREE),
 			branch_get_color(BRANCH_COLOR_LOCAL));
 	strbuf_addf(&remote, "  %s",
@@ -447,7 +453,7 @@ static char *build_format(struct ref_filter *filter, int maxwidth, const char *r
 
 		if (filter->verbose > 1)
 		{
-			strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)",
+			strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(currentworktree)%%(then)%%(else)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)%%(end)",
 				    branch_get_color(BRANCH_COLOR_WORKTREE), branch_get_color(BRANCH_COLOR_RESET));
 			strbuf_addf(&local, "%%(if)%%(upstream)%%(then)[%s%%(upstream:short)%s%%(if)%%(upstream:track)"
 				    "%%(then): %%(upstream:track,nobracket)%%(end)] %%(end)%%(contents:subject)",
t/t3203-branch-output.sh +21 -1
index debfac5f26..5541f1429b 100755
@@ -456,6 +456,23 @@ test_expect_success 'branch being rebased in a worktree is marked' '
 	test_cmp expect actual
 '
 
+test_expect_success 'branch being rebased is not marked in its own worktree' '
+	test_when_finished "git -C rebase_dir rebase --abort; rm -rf rebase_dir; git worktree prune; git branch -D rebasing" &&
+	git worktree add -b rebasing rebase_dir branch-two &&
+	(
+		cd rebase_dir &&
+		git commit --allow-empty -m rebase-me &&
+		test_must_fail git rebase -f -x false HEAD~1 &&
+		git branch --list rebasing >actual &&
+		echo "  rebasing" >expect &&
+		test_cmp expect actual &&
+		git branch -vv --list rebasing >actual &&
+		test_grep ! "$(pwd)" actual &&
+		git branch >actual &&
+		test_grep "^\* (no branch, rebasing rebasing)" actual
+	)
+'
+
 test_expect_success 'branch being bisected in a worktree is marked' '
 	test_when_finished "git -C bisect_dir bisect reset; rm -rf bisect_dir; git worktree prune; git branch -D bisecting" &&
 	git worktree add -b bisecting bisect_dir branch-two &&
@@ -464,7 +481,10 @@ test_expect_success 'branch being bisected in a worktree is marked' '
 		git commit --allow-empty -m bisect-one &&
 		git commit --allow-empty -m bisect-two &&
 		git bisect start HEAD HEAD~2 &&
-		test_must_fail git symbolic-ref -q HEAD
+		test_must_fail git symbolic-ref -q HEAD &&
+		git branch --list bisecting >actual &&
+		echo "  bisecting" >expect &&
+		test_cmp expect actual
 	) &&
 	git branch --list bisecting >actual &&
 	echo "+ bisecting" >expect &&
Signature · 1 line
2.56.0
#52 lore raw

Re: [PATCH v5 5/5] branch: do not mark the branch the current worktree is rebasing

Quoted 2 lines · Jasper Mayone

Since "ref-filter: name the worktree of a branch being rebased or bisected", "git branch" marks a branch with "+" when a worktree is

It cannot be avoided but it is awkward that we have to refer to a commit without a carved-into-stone object name yet. I wonder if

Since "ref-filter: name ..." that is a few commits ago in this series, ...

or something along that line would help?

Quoted 3 lines

rebasing or bisecting it. In that worktree itself, the list already starts with "* (no branch, rebasing topic)", so a "+ topic" line below it shows the same branch twice.

Two comments.

- in what context the command "marks a branch" is unclear. Are you talking about "git branch --list" output?

- does this talk about a regression in the middle of a series? Can we avoid such a regression by reordering commits in some way?

I seem to have ~600-700 local branches in the repository I usually work in (with a handful of worktrees), and I do see the list starts with

* (no branch, bisect started on jm/worktree-rebase-bisect-checked-out) ab/describe-no-i18n-of-debug-messages ab/index-pack-retain-child-bases
...

but by the time I scroll down to see the branches around it, I suspect

...
jk/test-lazy-prereq-heredoc
jk/unit-tests-via-test-lib
jk/xdiff-size_t
jm/t0213-skip-emulated-ancestry-tests
jm/worktree-rebase-bisect-checked-out
jr/bisect-custom-terms-in-output
js/adjust-tests-to-explicitly-access-bare-repo
...

that I would appreciate the branch currently being bisected marked as such in the list, together with any other branches being bisected in other worktrees.

So, unless I am missing a use case this change is trying to cater to, I am a bit negative on this change. If the [4/5] were solely to support this step, then stopping the series at [3/5] might be sufficient.

Thanks.

#53 lore raw

Re: [PATCH v5 5/5] branch: do not mark the branch the current worktree is rebasing

Quoted 8 lines · Junio C Hamano

that I would appreciate the branch currently being bisected marked as such in the list, together with any other branches being bisected in other worktrees.

So, unless I am missing a use case this change is trying to cater to, I am a bit negative on this change. If the [4/5] were solely to support this step, then stopping the series at [3/5] might be sufficient.

You are not missing a use case. The only reason for this step was that the branch shows up twice in the worktree that rebases it, and with a long list your point wins: the "+" line is the one you see next to the other branches.

[4/5] exists only to support this step, so please drop both and stop the series at [3/5]. Your comments on [1/5] and [2/5] do not ask for a change in this series, so I do not plan to send a v6 unless you want one.

Thanks
Jasper

#54 lore raw

Re: [PATCH v5 0/5] worktree: treat a branch being rebased or bisected as checked out

In reply to Jasper Mayone
Quoted 16 lines · Jasper Mayone

While a worktree is rebasing or bisecting a branch, its HEAD is detached. "git worktree add" and "git branch -d" already treat the branch as checked out there, but "git worktree remove" deletes such a worktree when its files are clean, and %(worktreepath) and "git branch" do not show which worktree has the branch.

Patch 1 makes "git worktree remove" refuse a worktree in the middle of an operation unless --force is given. Patch 2 documents how to read %(worktreepath) safely. Patch 3 makes %(worktreepath) name the worktree that is rebasing or bisecting a branch. Patch 4 adds %(currentworktree), and patch 5 uses it so that "git branch" does not mark that branch with "+" in the worktree that is rebasing it.

Quoted 6 lines

Changes since v4 [1]:

* Patch 1: each item in the list of cases that need --force is now a complete sentence, and all the commands are in the same font, as Phillip asked. Ben was happy with the old wording, and I hope this suits both of you.

It was a tiny nit (for me at least) to begin with, but the new version is also OK by me.

#55 lore raw
In reply to Jasper Mayone

I wonder if we should relax (or allow relaxing) the requirements on worktree branches overall?

I noticed that I can't check out a branch that is checked out in another worktree. Which seems a bit ridiculous because two regular repos of the same upstream would never enforce that.

AI loves worktress, so I suspect we'll see more of these discussions in the future.

Harald

#56 lore raw
Quoted 6 lines · Harald Nordgren

I wonder if we should relax (or allow relaxing) the requirements on worktree branches overall?

I noticed that I can't check out a branch that is checked out in another worktree. Which seems a bit ridiculous because two regular repos of the same upstream would never enforce that.

Because your repository updating what commit your 'main' points at would not affect my repository if they track the same upstream.

Worktrees are different. If you allow your two worktrees to check out the same 'main', and one of them makes a commit on top, you know what happens, right?

Quoted 2 lines

AI loves worktress, so I suspect we'll see more of these discussions in the future.

I think that was asked and answered already. "worktree add -d" is your friend.

#57 lore raw
Quoted 10 lines
Quoted 3 lines

I noticed that I can't check out a branch that is checked out in another worktree. Which seems a bit ridiculous because two regular repos of the same upstream would never enforce that.

Because your repository updating what commit your 'main' points at would not affect my repository if they track the same upstream.

Worktrees are different. If you allow your two worktrees to check out the same 'main', and one of them makes a commit on top, you know what happens, right?

I didn't. I read up on it now, and yes it's hairy. I withdraw my point here.

Quoted 5 lines
Quoted 2 lines

AI loves worktress, so I suspect we'll see more of these discussions in the future.

I think that was asked and answered already. "worktree add -d" is your friend.

Ok.

Harald