Skip to content

Commit 06aa1cd

Browse files
authored
Merge pull request #2361 from gitpython-developers/gixpython-update
Update the Gix backend to GixPython 0.4.0
2 parents 60a2715 + dc544f3 commit 06aa1cd

13 files changed

Lines changed: 245 additions & 39 deletions

‎.github/workflows/pythonpackage.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ jobs:
8282
- name: Prepare Rust for GixPython source builds
8383
id: rust
8484
run: |
85-
# GixPython 0.3.0 publishes macOS wheels only and needs Rust >= 1.89.
85+
# GixPython 0.4.0 publishes macOS wheels only and needs Rust >= 1.95.
8686
rustup toolchain install stable --profile minimal
8787
rustup default stable
8888
rustc --version

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ optional `gix` extra in a virtual environment:
2424
python -m pip install ".[gix]"
2525
```
2626

27-
The extra installs **GixPython 0.3.0** from PyPI; its Python import name is `gix`.
27+
The extra installs **GixPython 0.4.0** from PyPI; its Python import name is `gix`.
2828
Set `GIT_PYTHON_BACKEND=gix` **before importing GitPython**, either in your
2929
environment or in Python:
3030

@@ -48,8 +48,8 @@ Explicit `gix` selection fails if GixPython cannot be imported.
4848
3.8 or newer; on Python 3.8–3.10 the extra omits GixPython and uses CLI.
4949
- **Git 2.52 or newer**, available in `PATH` or selected with
5050
`GIT_PYTHON_GIT_EXECUTABLE`, remains required for CLI fallbacks.
51-
- GixPython 0.3.0 publishes **macOS wheels**. On **Linux and Windows**, installation
52-
builds its released source distribution and requires **Rust 1.89 or newer** and
51+
- GixPython 0.4.0 publishes **macOS wheels**. On **Linux and Windows**, installation
52+
builds its released source distribution and requires **Rust 1.95 or newer** and
5353
a **system linker**. Default hashing, compression and HTTPS dependencies use
5454
pure Rust and do not require a C/C++ compiler.
5555

‎doc/gix-backend.md‎

Lines changed: 35 additions & 11 deletions
Large diffs are not rendered by default.

‎git/_backend.py‎

Lines changed: 45 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,15 @@ def _canonical_repository(repo: Any) -> Any:
168168
def _check_revision_grammar(ref: str) -> None:
169169
if ref.startswith(":/") or "^{/" in ref or "-dirty" in ref or re.search(r"-\d+-g[0-9a-fA-F]+|^[0-9a-fA-F]+-", ref):
170170
raise _Unsupported("revision grammar differences (GIX-17)")
171+
prefix, opener, remainder = ref.partition("@{")
172+
if opener and ":" not in prefix:
173+
selector, closer, _ = remainder.partition("}")
174+
if closer and not (
175+
re.fullmatch(r"[0-9]+", selector)
176+
or (not prefix and re.fullmatch(r"-[0-9]+", selector))
177+
or selector.lower() in {"u", "upstream", "p", "push"}
178+
):
179+
raise _Unsupported("textual reflog dates (GIX-39)")
171180

172181

173182
def _oid(repo: Any, ref: Any, env: Optional[Dict[str, Any]] = None) -> Any:
@@ -245,9 +254,16 @@ def object_metadata(command: Any, oid: str, kind: str) -> Any:
245254
else ((data.tagger, result["tagger"]),)
246255
)
247256
for raw, signature in signatures:
248-
# Gix reads a time zone of 0 with trailing fields (GIX-34); accept either UTC sign.
249-
if signature is not None and not raw.replace(b" -0000", b" +0000").endswith(b"> " + _date(signature)):
250-
raise _Unsupported("signature trailing fields (GIX-34)")
257+
if signature is not None:
258+
if signature.time.seconds < 0:
259+
raise _Unsupported("negative signature timestamp (GIX-42)")
260+
identity, _, date = raw.rpartition(b">")
261+
if b">" in signature.email or identity != signature.name + b" <" + signature.email:
262+
raise _Unsupported("signature identity differs from raw header (GIX-43)")
263+
# Gix can decode a short offset such as +020 as UTC.
264+
date = date.replace(b" -0000", b" +0000", 1)
265+
if not (date + b" ").startswith(b" " + _date(signature) + b" "):
266+
raise _Unsupported("signature date differs from raw header (GIX-38)")
251267
except _Unsupported as exc:
252268
return _fallback(kind + ".decode", str(exc))
253269
except gix.Error as exc:
@@ -311,20 +327,27 @@ def _rev_parse(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes:
311327
return str(_oid(repo, args[-1], kwargs.get("env"))).encode("ascii") + b"\n"
312328

313329

330+
_LS_TREE_MODES = {
331+
"blob": b"100644 blob",
332+
"exe": b"100755 blob",
333+
"link": b"120000 blob",
334+
"tree": b"040000 tree",
335+
"commit": b"160000 commit",
336+
}
337+
338+
314339
def _ls_tree(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes:
315340
if len(args) != 3 or args[:2] != ["-z", "--full-tree"]:
316341
raise _Unsupported("tree options")
317342
with repo.find_tree(_oid(repo, args[2])).iter() as entries:
318-
return b"".join(
319-
b"%06o %s %s\t%s\0"
320-
% (
321-
entry.mode(),
322-
b"tree" if entry.kind() == "tree" else b"commit" if entry.kind() == "commit" else b"blob",
323-
str(entry.id()).encode("ascii"),
324-
entry.filename(),
343+
records = []
344+
for entry in entries:
345+
if entry.mode() == 0:
346+
raise _Unsupported("ambiguous zero tree entry mode (GIX-41)")
347+
records.append(
348+
b"%s %s\t%s\0" % (_LS_TREE_MODES[entry.kind()], str(entry.id()).encode("ascii"), entry.filename())
325349
)
326-
for entry in entries
327-
)
350+
return b"".join(records)
328351

329352

330353
def check_ref_name(name: str) -> Any:
@@ -528,15 +551,22 @@ def is_dirty(command: Any, index: bool, working_tree: bool, untracked: bool, sub
528551
for item in entries:
529552
if item.summary() is None:
530553
continue
554+
details = item.details
531555
if item.kind == "TreeIndex":
532-
if index and (submodules or item.details["entry_mode"] != 0o160000):
556+
if index and (submodules or details["entry_mode"] != 0o160000):
533557
dirty = True
534558
break
535-
elif item.details["kind"] == "DirectoryContents":
536-
if untracked and item.details["entry"]["status"] == "Untracked":
559+
elif details["kind"] == "DirectoryContents":
560+
if untracked and details["entry"]["status"] == "Untracked":
537561
dirty = True
538562
break
539563
elif working_tree:
564+
change = details.get("status", {})
565+
if (
566+
change.get("change") == "SubmoduleModification"
567+
and not change["status"].state["superproject_configuration"]
568+
):
569+
raise _Unsupported("embedded repository diff policy (GIX-40)")
540570
dirty = True
541571
break
542572
except _Unsupported as exc:

‎gix-requirements.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
GixPython==0.3.0 ; python_version >= "3.11"
1+
GixPython==0.4.0 ; python_version >= "3.11"

‎test-requirements.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
coverage[toml]
2-
GixPython==0.3.0 ; python_version >= "3.11"
2+
GixPython==0.4.0 ; python_version >= "3.11"
33
basedpyright==1.39.9 ; python_version >= "3.9" and sys_platform != "cygwin"
44
ddt >= 1.1.1, != 1.4.3
55
mock # Also needed to typecheck the Python 3.7 import branches.

‎test/test_commit.py‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -703,9 +703,55 @@ def test_deserialization_reads_date_after_email(self):
703703
)
704704
if _backend.name == "gix":
705705
for kind in ("commit", "tag"):
706-
key = (kind + ".decode", "CLI: signature trailing fields (GIX-34)")
706+
key = (kind + ".decode", "native")
707707
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + 1)
708708

709+
def test_deserialization_preserves_email_whitespace(self):
710+
with fixture_repo("commit.sh", "spaced-email") as repo:
711+
root = Path(repo.working_dir).parent
712+
oid = (root / "object-id").read_text().strip()
713+
tag_oid = (root / "tag-id").read_text().strip()
714+
self.assertEqual(repo.git.show("-s", "--format=[%ae][%ce]", oid), "[ a@example.com ][ c@example.com ]")
715+
before = _backend.statistics()
716+
commit = Commit(repo, bytes.fromhex(oid))
717+
self.assertEqual((commit.author.email, commit.committer.email), (" a@example.com ", " c@example.com "))
718+
self.assertEqual(TagObject(repo, bytes.fromhex(tag_oid)).tagger.email, " t@example.com ")
719+
if _backend.name == "gix":
720+
for key in (
721+
("commit.decode", "CLI: signature identity differs from raw header (GIX-43)"),
722+
("tag.decode", "native"),
723+
):
724+
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + 1)
725+
726+
def test_deserialization_negative_timestamp_matches_git(self):
727+
with fixture_repo("commit.sh", "negative-date") as repo:
728+
root = Path(repo.working_dir).parent
729+
oid = (root / "object-id").read_text().strip()
730+
tag_oid = (root / "tag-id").read_text().strip()
731+
self.assertEqual(repo.git.show("-s", "--format=%ad", "--date=raw", oid), "")
732+
before = _backend.statistics()
733+
commit = Commit(repo, bytes.fromhex(oid))
734+
self.assertEqual((commit.authored_date, commit.author_tz_offset), (0, 0))
735+
self.assertEqual((commit.committed_date, commit.committer_tz_offset), (0, 0))
736+
tag = TagObject(repo, bytes.fromhex(tag_oid))
737+
self.assertEqual((tag.tagged_date, tag.tagger_tz_offset), (0, 0))
738+
if _backend.name == "gix":
739+
for kind in ("commit", "tag"):
740+
key = (kind + ".decode", "CLI: negative signature timestamp (GIX-42)")
741+
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + 1)
742+
743+
def test_deserialization_short_offset_matches_git(self):
744+
with fixture_repo("commit.sh", "short-offset") as repo:
745+
oid = (Path(repo.working_dir).parent / "object-id").read_text().strip()
746+
self.assertEqual(repo.git.show("-s", "--format=%ad", "--date=raw", oid), "1112591163 +0020")
747+
before = _backend.statistics()
748+
commit = Commit(repo, bytes.fromhex(oid))
749+
self.assertEqual((commit.authored_date, commit.author_tz_offset), (1112591163, -1200))
750+
self.assertEqual((commit.committed_date, commit.committer_tz_offset), (1112591163, -1200))
751+
if _backend.name == "gix":
752+
key = ("commit.decode", "CLI: signature date differs from raw header (GIX-38)")
753+
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + 1)
754+
709755
def test_deserialization_negative_zero_offset_stays_native(self):
710756
with fixture_repo("commit.sh", "zero-offset") as repo:
711757
root = Path(repo.working_dir).parent

‎test/test_gix_backend.py‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
import pytest
1313

14-
from git import Actor, Commit, Git, Reference, Repo, SymbolicReference, _backend
14+
from git import Actor, Commit, Git, Reference, Repo, SymbolicReference, Tree, _backend
1515
from git.exc import GitCommandError, InvalidGitRepositoryError, UnsafeOptionError
1616
from git.index.fun import run_commit_hook
1717
from git.repo.fun import find_submodule_git_dir, find_worktree_git_dir, is_git_dir
@@ -264,6 +264,37 @@ def test_native_objects_trees_commits_and_index_reads(repo):
264264
assert commit.replace(message="changed").message == "changed"
265265

266266

267+
@pytest.mark.parametrize("object_format", ["sha1", "sha256"])
268+
@pytest.mark.parametrize("entry_types", ["blob-and-link", "gitlink"])
269+
def test_native_tree_entry_modes_match_git(object_format, entry_types):
270+
with fixture_repo("tree-modes.sh", object_format, entry_types) as repo:
271+
oid = (Path(repo.working_dir).parent / "tree-id").read_text().strip()
272+
lines = repo.git.ls_tree(oid).splitlines()
273+
expected = [(line.split("\t")[1], int(line.split()[0], 8)) for line in lines]
274+
with patch.object(Git, "execute", side_effect=AssertionError("unexpected tree-listing CLI call")):
275+
tree = Tree(repo, bytes.fromhex(oid), path="")
276+
assert [(entry.path, entry.mode) for entry in tree] == expected
277+
278+
279+
@pytest.mark.parametrize("object_format", ["sha1", "sha256"])
280+
@pytest.mark.parametrize("entry_types", ["missing-mode", "zero-mode"])
281+
def test_ambiguous_tree_entry_mode_uses_git(object_format, entry_types):
282+
with fixture_repo("tree-modes.sh", object_format, entry_types) as repo:
283+
oid = (Path(repo.working_dir).parent / "tree-id").read_text().strip()
284+
tree = Tree(repo, bytes.fromhex(oid), path="")
285+
before = _backend.statistics()
286+
if entry_types == "missing-mode":
287+
with pytest.raises(GitCommandError, match="malformed mode"):
288+
repo.git.ls_tree(oid)
289+
with pytest.raises(GitCommandError, match="malformed mode"):
290+
list(tree)
291+
else:
292+
assert "160000 commit" in repo.git.ls_tree(oid)
293+
assert tree["module"].mode == 0o160000
294+
key = ("ls_tree", "CLI: ambiguous zero tree entry mode (GIX-41)")
295+
assert _backend.statistics().get(key, 0) == before.get(key, 0) + 1
296+
297+
267298
def test_native_metadata_paths_match_git_in_each_worktree(repo):
268299
tmp_path = Path(repo.working_dir).parent
269300
linked_path = tmp_path / "linked"
@@ -376,6 +407,17 @@ def snapshot():
376407
assert snapshot() == expected
377408

378409

410+
@pytest.mark.parametrize("object_format", ["sha1", "sha256"])
411+
@pytest.mark.parametrize("syntax", ["implicit-extra", "inline-extra", "comment-in-key"])
412+
def test_submodule_configuration_rejects_lines_git_rejects(object_format, syntax):
413+
with fixture_repo("submodule-rejected-lines.sh", object_format, syntax) as repo:
414+
with pytest.raises(GitCommandError, match="bad config line"):
415+
repo.git.config("--file", ".gitmodules", "--list")
416+
data = (Path(repo.working_dir) / ".gitmodules").read_bytes()
417+
with pytest.raises(gix.Error):
418+
gix.ModulesFile.from_bytes(data)
419+
420+
379421
def test_native_revision_path_and_mode_match_cli(repo):
380422
blob = repo.head.commit.tree["dir/file"]
381423
revisions = ["HEAD:", "HEAD:dir/", "HEAD:dir/file", "HEAD:executable", "HEAD:link", ":executable", ":0:link"]
@@ -718,6 +760,16 @@ def test_native_status_tracks_submodule_dirtiness(repo):
718760
assert dirty == [repo.is_dirty(**option) for option in options]
719761

720762

763+
@pytest.mark.parametrize("target", ["untracked", "file"])
764+
def test_embedded_status_uses_git_diff_policy(repo, target):
765+
expected = target == "file"
766+
assert bool(repo.git.diff("--raw")) == expected
767+
before = _backend.statistics()
768+
assert repo.is_dirty() == expected
769+
key = ("Repo.is_dirty", "CLI: embedded repository diff policy (GIX-40)")
770+
assert _backend.statistics().get(key, 0) == before.get(key, 0) + 1
771+
772+
721773
@pytest.mark.parametrize("error", [OSError(22, "Invalid filename"), PermissionError(13, "Permission denied")])
722774
def test_ignore_metadata_errors_retain_cli(error):
723775
with fixture_repo("repo.sh", "ignore-verbatim") as repo:

‎test/test_rev_parse.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import pytest
1212
from gitdb.exc import BadName
1313

14-
from git import Commit, Repo, GitCommandError
14+
from git import Commit, Repo, GitCommandError, _backend
1515
from test.lib.fixtures import fixture_repo, read_only_fixture
1616

1717

@@ -154,6 +154,15 @@ def test_rev_parse_reflog_selectors(rev_parse_repo):
154154

155155
assert repo.rev_parse("%s@{upstream}" % main.name) == merge
156156

157+
before = _backend.statistics()
158+
with pytest.raises((BadName, GitCommandError)):
159+
repo.rev_parse("HEAD@{never}")
160+
revision = "HEAD@{1970-01-01 00:00:01 +0000}"
161+
assert repo.rev_parse(revision).hexsha == repo.git.rev_parse("--verify", revision)
162+
if _backend.name == "gix":
163+
key = ("rev_parse", "CLI: textual reflog dates (GIX-39)")
164+
assert _backend.statistics().get(key, 0) == before.get(key, 0) + 2
165+
157166

158167
def test_rev_parse_commit_message_search(rev_parse_repo):
159168
repo = rev_parse_repo["repo"]

‎tests/fixtures/commit.sh‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,19 +57,23 @@ case "$1" in
5757
raw)
5858
git hash-object --literally -w -t commit "$2" > ../object-id
5959
;;
60-
trailing-date|zero-offset)
60+
trailing-date|zero-offset|short-offset|negative-date|spaced-email)
6161
date='1112591163 +0200 1700000000 -0500'
6262
if [ "$1" = zero-offset ]; then date='1112591163 -0000'; fi
63+
if [ "$1" = short-offset ]; then date='1112591163 +020'; fi
64+
if [ "$1" = negative-date ]; then date='-1 +0200 1700000000 -0500'; fi
65+
space=''
66+
if [ "$1" = spaced-email ]; then space=' '; fi
6367
tree=$(git mktree </dev/null)
6468
{
6569
printf 'tree %s\n' "$tree"
66-
printf 'author A <a@example.com> %s\n' "$date"
67-
printf 'committer C <c@example.com> %s\n' "$date"
70+
printf 'author A <%sa@example.com%s> %s\n' "$space" "$space" "$date"
71+
printf 'committer C <%sc@example.com%s> %s\n' "$space" "$space" "$date"
6872
printf '\nmessage\n'
6973
} | git hash-object --literally -w -t commit --stdin > ../object-id
7074
{
7175
printf 'object %s\ntype commit\ntag v1\n' "$(cat ../object-id)"
72-
printf 'tagger T <t@example.com> %s\n' "$date"
76+
printf 'tagger T <%st@example.com%s> %s\n' "$space" "$space" "$date"
7377
printf '\nmessage\n'
7478
} | git hash-object --literally -w -t tag --stdin > ../tag-id
7579
git update-ref refs/tags/v1 "$(cat ../tag-id)"

0 commit comments

Comments
 (0)