Commit

a6de316efde124a132d38e50c6407477df47f9cd

worktree add: trim slashes when deriving branch name from path

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 <l.s.r@web.de>
Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe <l.s.r@web.de> · 2026-08-25 18:03 UTC · committed by Junio C Hamano

Browse files
2 files changed, +15 −2
modified builtin/worktree.c
@@ -768,7 +768,7 @@ static char *dwim_branch(const char *path, char **new_branch)
768 768 int n;
769 769 int branch_exists;
770 770 const char *s = worktree_basename(path, &n);
771 - char *branchname = xstrndup(s, n);
771 + char *branchname = xmemdupz(s, path + n - s);
772 772 struct strbuf ref = STRBUF_INIT;
773 773
774 774 branch_exists = !check_branch_ref(&ref, branchname) &&
@@ -877,7 +877,7 @@ static int add(int ac, const char **av, const char *prefix,
877 877 if (opts.orphan && !new_branch) {
878 878 int n;
879 879 const char *s = worktree_basename(path, &n);
880 - new_branch = new_branch_to_free = xstrndup(s, n);
880 + new_branch = new_branch_to_free = xmemdupz(s, path + n - s);
881 881 } else if (opts.orphan) {
882 882 ; /* no-op */
883 883 } else if (opts.detach) {
modified t/t2400-worktree-add.sh
@@ -298,6 +298,11 @@ test_expect_success '"add" with <branch> omitted' '
298 298 test_cmp_rev HEAD bat
299 299 '
300 300
301 + test_expect_success '"add" with trailing slash and <branch> omitted' '
302 + git worktree add waffle/bit/ &&
303 + test_cmp_rev HEAD bit
304 + '
305 +
301 306 test_expect_success '"add" checks out existing branch of dwimd name' '
302 307 git branch dwim HEAD~1 &&
303 308 git worktree add dwim &&
@@ -388,6 +393,14 @@ test_expect_success '"add --orphan (no -b)"' '
388 393 test_cmp expected actual
389 394 '
390 395
396 + test_expect_success '"add --orphan with trailing slash (no -b)"' '
397 + test_when_finished "git worktree remove -f -f neworphan" &&
398 + git worktree add --orphan ./neworphan/ &&
399 + echo refs/heads/neworphan >expected &&
400 + git -C neworphan symbolic-ref HEAD >actual &&
401 + test_cmp expected actual
402 + '
403 +
391 404 test_expect_success '"add --orphan --quiet"' '
392 405 test_when_finished "git worktree remove -f -f orphandir" &&
393 406 git worktree add --quiet --orphan -b neworphan orphandir 2>log.actual &&