Skip to content

Commit 2696c5c

Browse files
committed
repository: make check if repo is a worktree more strict
To determine if a repository is a worktree or not, we currently check for the existence of a "gitdir" file inside of the repository's gitdir. While this is sufficient for non-broken repositories, we have at least one case of a subtly broken repository where there exists a gitdir file inside of a gitmodule. This will cause us to misidentify the submodule as a worktree. While this is not really a fault of ours, we can do better here by observing that a repository can only ever be a worktree iff its common directory and dotgit directory are different. This allows us to make our check whether a repo is a worktree or not more strict by doing a simple string comparison of these two directories. This will also allow us to do the right thing in the above case of a broken repository, as for submodules these directories will be the same. At the same time, this allows us to skip the `stat` check for the "gitdir" file for most repositories.
1 parent 9f9fd05 commit 2696c5c

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/repository.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -763,6 +763,13 @@ static int repo_is_worktree(unsigned *out, const git_repository *repo)
763763
git_buf gitdir_link = GIT_BUF_INIT;
764764
int error;
765765

766+
/* Worktrees cannot have the same commondir and gitdir */
767+
if (repo->commondir && repo->gitdir
768+
&& !strcmp(repo->commondir, repo->gitdir)) {
769+
*out = 0;
770+
return 0;
771+
}
772+
766773
if ((error = git_buf_joinpath(&gitdir_link, repo->gitdir, "gitdir")) < 0)
767774
return -1;
768775

tests/submodule/open.c

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,22 @@ void test_submodule_open__direct_open_succeeds(void)
6969

7070
git_buf_free(&path);
7171
}
72+
73+
void test_submodule_open__direct_open_succeeds_for_broken_sm_with_gitdir(void)
74+
{
75+
git_buf path = GIT_BUF_INIT;
76+
77+
/*
78+
* This is actually not a valid submodule, but we
79+
* encountered at least one occasion where the gitdir
80+
* file existed inside of a submodule's gitdir. As we are
81+
* now able to open these submodules correctly, we still
82+
* add a test for this.
83+
*/
84+
cl_git_mkfile("submod2/.git/modules/sm_unchanged/gitdir", ".git");
85+
cl_git_pass(git_buf_joinpath(&path, git_repository_workdir(g_parent), "sm_unchanged"));
86+
cl_git_pass(git_repository_open(&g_child, path.ptr));
87+
assert_sm_valid(g_parent, g_child, "sm_unchanged");
88+
89+
git_buf_free(&path);
90+
}

0 commit comments

Comments
 (0)