Skip to content

Commit 63748ba

Browse files
committed
Add GitRepository.git_dir
We cannot just assume that .git/ in a git repo is the git directory.
1 parent 964d73a commit 63748ba

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

tests/mixin_git.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,39 @@ def __init__(self, repo_dir):
2424
'''
2525
self.repo_dir = repo_dir
2626

27+
@property
28+
def git_dir(self):
29+
'''
30+
The path for the `.git` directory for this repository.
31+
32+
NOTE: This is broken for submodules as we don't really need support for
33+
that at the moment!
34+
'''
35+
with self.work_dir():
36+
# Simple, this is a normal .git repo with a .git directory.
37+
if os.path.isdir('.git'):
38+
return os.path.abspath('.git')
39+
40+
# A worktree or a submodule! Damn!
41+
with open('.git') as git_file:
42+
content = git_file.read().rstrip()
43+
intro = 'gitdir: '
44+
assert content.startswith(intro), \
45+
'Unexpected content of .git file: {}'.format(content)
46+
worktree_git_dir = content[len(intro):]
47+
48+
# Now we have the git directory for this worktree's branch, it should
49+
# be something like PROJECT/.git/worktrees/WORKTREE-DIR-NAME.
50+
# We just rely on the path structure to extract the main dir, this is
51+
# good enough for tests.
52+
# Note that we ignore submodules for now as we don't really need to
53+
# support them.
54+
worktree_git_dir = os.path.normpath(worktree_git_dir)
55+
components = worktree_git_dir.split(os.path.sep)
56+
assert components[-2] == 'worktrees'
57+
# Everything before the worktrees directory.
58+
return os.path.sep.join(components[:-2])
59+
2760
def work_dir(self):
2861
return testutils.WorkDir(self.repo_dir)
2962

0 commit comments

Comments
 (0)