Skip to content

IndexFile._to_relative_path - fix case where absolute path gets stripped of trailing slash #2012

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 12, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion git/index/base.py
Original file line number Diff line number Diff line change
@@ -655,7 +655,10 @@ def _to_relative_path(self, path: PathLike) -> PathLike:
raise InvalidGitRepositoryError("require non-bare repository")
if not osp.normpath(str(path)).startswith(str(self.repo.working_tree_dir)):
raise ValueError("Absolute path %r is not in git repository at %r" % (path, self.repo.working_tree_dir))
return os.path.relpath(path, self.repo.working_tree_dir)
result = os.path.relpath(path, self.repo.working_tree_dir)
if str(path).endswith(os.sep) and not result.endswith(os.sep):
result += os.sep
return result

def _preprocess_add_items(
self, items: Union[PathLike, Sequence[Union[PathLike, Blob, BaseIndexEntry, "Submodule"]]]
22 changes: 22 additions & 0 deletions test/test_index.py
Original file line number Diff line number Diff line change
@@ -16,6 +16,7 @@
import subprocess
import sys
import tempfile
from unittest import mock

from gitdb.base import IStream

@@ -1015,6 +1016,27 @@ class Mocked:
rel = index._to_relative_path(path)
self.assertEqual(rel, os.path.relpath(path, root))

def test__to_relative_path_absolute_trailing_slash(self):
repo_root = os.path.join(osp.abspath(os.sep), "directory1", "repo_root")

class Mocked:
bare = False
git_dir = repo_root
working_tree_dir = repo_root

repo = Mocked()
path = os.path.join(repo_root, f"directory2{os.sep}")
index = IndexFile(repo)

expected_path = f"directory2{os.sep}"
actual_path = index._to_relative_path(path)
self.assertEqual(expected_path, actual_path)

with mock.patch("git.index.base.os.path") as ospath_mock:
ospath_mock.relpath.return_value = f"directory2{os.sep}"
actual_path = index._to_relative_path(path)
self.assertEqual(expected_path, actual_path)

@pytest.mark.xfail(
type(_win_bash_status) is WinBashStatus.Absent,
reason="Can't run a hook on Windows without bash.exe.",