From a6de316efde124a132d38e50c6407477df47f9cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Scharfe?= Date: Tue, 25 Aug 2026 20:03:49 +0200 Subject: [PATCH] worktree add: trim slashes when deriving branch name from path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit worktree_basename() sets `n` to the length of `path` without trailing path separators, not to the length of the basename. This matters when deriving a branch name from a path with more than one component. E.g.: path: /new/worktree/ s: ^ n: |-----------| So here xstrndup(s, n) copies up to 13 characters from "worktree/", effectively to the end of the string, including the trailing dash. Path separators are not allowed at the end of branch names, so strip them off by calculating the basename length and extracting just that part. Signed-off-by: René Scharfe Signed-off-by: Junio C Hamano --- builtin/worktree.c | 4 ++-- t/t2400-worktree-add.sh | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/builtin/worktree.c b/builtin/worktree.c index 214de50d4c..e5b7d6f5ec 100644 --- a/builtin/worktree.c +++ b/builtin/worktree.c @@ -768,7 +768,7 @@ static char *dwim_branch(const char *path, char **new_branch) int n; int branch_exists; const char *s = worktree_basename(path, &n); - char *branchname = xstrndup(s, n); + char *branchname = xmemdupz(s, path + n - s); struct strbuf ref = STRBUF_INIT; branch_exists = !check_branch_ref(&ref, branchname) && @@ -877,7 +877,7 @@ static int add(int ac, const char **av, const char *prefix, if (opts.orphan && !new_branch) { int n; const char *s = worktree_basename(path, &n); - new_branch = new_branch_to_free = xstrndup(s, n); + new_branch = new_branch_to_free = xmemdupz(s, path + n - s); } else if (opts.orphan) { ; /* no-op */ } else if (opts.detach) { diff --git a/t/t2400-worktree-add.sh b/t/t2400-worktree-add.sh index 4ffdd56fb4..9542a17cf3 100755 --- a/t/t2400-worktree-add.sh +++ b/t/t2400-worktree-add.sh @@ -298,6 +298,11 @@ test_expect_success '"add" with omitted' ' test_cmp_rev HEAD bat ' +test_expect_success '"add" with trailing slash and omitted' ' + git worktree add waffle/bit/ && + test_cmp_rev HEAD bit +' + test_expect_success '"add" checks out existing branch of dwimd name' ' git branch dwim HEAD~1 && git worktree add dwim && @@ -388,6 +393,14 @@ test_expect_success '"add --orphan (no -b)"' ' test_cmp expected actual ' +test_expect_success '"add --orphan with trailing slash (no -b)"' ' + test_when_finished "git worktree remove -f -f neworphan" && + git worktree add --orphan ./neworphan/ && + echo refs/heads/neworphan >expected && + git -C neworphan symbolic-ref HEAD >actual && + test_cmp expected actual +' + test_expect_success '"add --orphan --quiet"' ' test_when_finished "git worktree remove -f -f orphandir" && git worktree add --quiet --orphan -b neworphan orphandir 2>log.actual &&