Merge commit

52e324c8d60c30b8ea3bac654f183bfb3467dfae

Merge branch 'rs/worktree-add-basename-fixes'

The string extraction logic for the branch name and worktree name
from the given path in 'git worktree add' has been corrected and
simplified to avoid out-of-bounds reads and improper handling of
trailing slashes.

* rs/worktree-add-basename-fixes:
  worktree add: let worktree_basename() return string copy
  worktree add: trim slashes when deriving branch name from path
  worktree add: reject separator-only path
  worktree add: don't read out of bounds in worktree_basename()

Junio C Hamano <gitster@pobox.com> · 2026-09-10 12:36 UTC

Browse files

Combined diff: only what this merge did beyond taking one side. Added lines are colored by the parent they came from; bold lines came from none of them; removed lines are red.

1 file changed, +22 −5
modified builtin/worktree.c
@@@ -764,34 -762,13 +763,32 @@@ static int dwim_orphan(const struct add
763 return 1;
764 }
765
- static char *dwim_branch(const char *path, char **new_branch)
766 + static void advise_disambiguating_remotes(const char *path, const char *branch,
767 + const struct string_list *matched_remote_names)
768 + {
769 + struct string_list_item *item;
770 +
771 + advise(_("Branch name '%s' appears in multiple remotes:"), branch);
772 + for_each_string_list_item(item, matched_remote_names) {
773 + advise(_(" %s"), item->string);
774 + }
775 + advise(_("If you meant to create a worktree from a remote tracking branch on\n"
776 + "<remote>, you can do so by:\n"
777 + "\n"
778 + " git worktree add -b %s %s <remote>/%s\n"
779 + "\n"
780 + "If you'd like to always prefer some remote, e.g. 'origin',\n"
781 + "consider setting checkout.defaultRemote=origin in your config."),
782 + branch, path, branch);
783 + }
784 +
785 + static char *dwim_branch(const struct add_opts *opts, const char *path, char **new_branch)
786 {
- int n;
787 int branch_exists;
- const char *s = worktree_basename(path, &n);
- char *branchname = xstrndup(s, n);
788 + char *branchname = worktree_basename_dup(path);
789 struct strbuf ref = STRBUF_INIT;
790
- branch_exists = !check_branch_ref(&ref, branchname) &&
791 + branch_exists = !check_branch_ref(the_repository, &ref, branchname) &&
792 refs_ref_exists(get_main_ref_store(the_repository),
793 ref.buf);
794 strbuf_release(&ref);