Handle diffs on a detached head #520

This commit is contained in:
Paul Gauthier 2024-04-11 10:24:51 -07:00
parent 5c10944054
commit c2b8b2355d
2 changed files with 40 additions and 4 deletions

View file

@ -137,11 +137,17 @@ class GitRepo:
def get_diffs(self, fnames=None): def get_diffs(self, fnames=None):
# We always want diffs of index and working dir # We always want diffs of index and working dir
current_branch_has_commits = False
try: try:
commits = self.repo.iter_commits(self.repo.active_branch) active_branch = self.repo.active_branch
current_branch_has_commits = any(commits) try:
except git.exc.GitCommandError: commits = self.repo.iter_commits(active_branch)
current_branch_has_commits = False current_branch_has_commits = any(commits)
except git.exc.GitCommandError:
pass
except TypeError:
pass
if not fnames: if not fnames:
fnames = [] fnames = []

View file

@ -53,6 +53,36 @@ class TestRepo(unittest.TestCase):
self.assertIn("index", diffs) self.assertIn("index", diffs)
self.assertIn("workingdir", diffs) self.assertIn("workingdir", diffs)
def test_diffs_detached_head(self):
with GitTemporaryDirectory():
repo = git.Repo()
fname = Path("foo.txt")
fname.touch()
repo.git.add(str(fname))
repo.git.commit("-m", "foo")
fname2 = Path("bar.txt")
fname2.touch()
repo.git.add(str(fname2))
repo.git.commit("-m", "bar")
fname3 = Path("baz.txt")
fname3.touch()
repo.git.add(str(fname3))
repo.git.commit("-m", "baz")
repo.git.checkout("HEAD^")
fname.write_text("index\n")
repo.git.add(str(fname))
fname2.write_text("workingdir\n")
git_repo = GitRepo(InputOutput(), None, ".")
diffs = git_repo.get_diffs()
self.assertIn("index", diffs)
self.assertIn("workingdir", diffs)
def test_diffs_between_commits(self): def test_diffs_between_commits(self):
with GitTemporaryDirectory(): with GitTemporaryDirectory():
repo = git.Repo() repo = git.Repo()