]> git.ipfire.org Git - thirdparty/git.git/commit
worktree: return allocated string from `get_worktree_git_dir()`
authorPatrick Steinhardt <ps@pks.im>
Fri, 7 Feb 2025 11:03:34 +0000 (12:03 +0100)
committerJunio C Hamano <gitster@pobox.com>
Fri, 7 Feb 2025 17:59:23 +0000 (09:59 -0800)
commit8e4710f011dce286d24838fdafd5ce52cfac5285
tree359727495fa9af9d22dcd7606d677d7f13ee5f61
parent3859e3965993493defd39cd54a2ab2097957e270
worktree: return allocated string from `get_worktree_git_dir()`

The `get_worktree_git_dir()` function returns a string constant that
does not need to be free'd by the caller. This string is computed for
three different cases:

  - If we don't have a worktree we return a path into the Git directory.
    The returned string is owned by `the_repository`, so there is no
    need for the caller to free it.

  - If we have a worktree, but no worktree ID then the caller requests
    the main worktree. In this case we return a path into the common
    directory, which again is owned by `the_repository` and thus does
    not need to be free'd.

  - In the third case, where we have an actual worktree, we compute the
    path relative to "$GIT_COMMON_DIR/worktrees/". This string does not
    need to be released either, even though `git_common_path()` ends up
    allocating memory. But this doesn't result in a memory leak either
    because we write into a buffer returned by `get_pathname()`, which
    returns one out of four static buffers.

We're about to drop `git_common_path()` in favor of `repo_common_path()`,
which doesn't use the same mechanism but instead returns an allocated
string owned by the caller. While we could adapt `get_worktree_git_dir()`
to also use `get_pathname()` and print the derived common path into that
buffer, the whole schema feels a lot like premature optimization in this
context. There are some callsites where we call `get_worktree_git_dir()`
in a loop that iterates through all worktrees. But none of these loops
seem to be even remotely in the hot path, so saving a single allocation
there does not feel worth it.

Refactor the function to instead consistently return an allocated path
so that we can start using `repo_common_path()` in a subsequent commit.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
branch.c
builtin/fsck.c
builtin/receive-pack.c
builtin/worktree.c
reachable.c
revision.c
worktree.c
worktree.h