Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion .github/workflows/pythonpackage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ jobs:
- name: Prepare Rust for GixPython source builds
id: rust
run: |
# GixPython 0.3.0 publishes macOS wheels only and needs Rust >= 1.89.
# GixPython 0.4.0 publishes macOS wheels only and needs Rust >= 1.95.
rustup toolchain install stable --profile minimal
rustup default stable
rustc --version
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ optional `gix` extra in a virtual environment:
python -m pip install ".[gix]"
```

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

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

Expand Down
46 changes: 35 additions & 11 deletions doc/gix-backend.md

Large diffs are not rendered by default.

60 changes: 45 additions & 15 deletions git/_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,15 @@ def _canonical_repository(repo: Any) -> Any:
def _check_revision_grammar(ref: str) -> None:
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):
raise _Unsupported("revision grammar differences (GIX-17)")
prefix, opener, remainder = ref.partition("@{")
if opener and ":" not in prefix:
selector, closer, _ = remainder.partition("}")
if closer and not (
re.fullmatch(r"[0-9]+", selector)
or (not prefix and re.fullmatch(r"-[0-9]+", selector))
or selector.lower() in {"u", "upstream", "p", "push"}
):
raise _Unsupported("textual reflog dates (GIX-39)")
Comment thread
Byron marked this conversation as resolved.
Resolved


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


_LS_TREE_MODES = {
"blob": b"100644 blob",
"exe": b"100755 blob",
"link": b"120000 blob",
"tree": b"040000 tree",
"commit": b"160000 commit",
}


def _ls_tree(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes:
if len(args) != 3 or args[:2] != ["-z", "--full-tree"]:
raise _Unsupported("tree options")
with repo.find_tree(_oid(repo, args[2])).iter() as entries:
return b"".join(
b"%06o %s %s\t%s\0"
% (
entry.mode(),
b"tree" if entry.kind() == "tree" else b"commit" if entry.kind() == "commit" else b"blob",
str(entry.id()).encode("ascii"),
entry.filename(),
records = []
for entry in entries:
if entry.mode() == 0:
raise _Unsupported("ambiguous zero tree entry mode (GIX-41)")
records.append(
b"%s %s\t%s\0" % (_LS_TREE_MODES[entry.kind()], str(entry.id()).encode("ascii"), entry.filename())
)
for entry in entries
)
return b"".join(records)


def check_ref_name(name: str) -> Any:
Expand Down Expand Up @@ -528,15 +551,22 @@ def is_dirty(command: Any, index: bool, working_tree: bool, untracked: bool, sub
for item in entries:
if item.summary() is None:
continue
details = item.details
if item.kind == "TreeIndex":
if index and (submodules or item.details["entry_mode"] != 0o160000):
if index and (submodules or details["entry_mode"] != 0o160000):
dirty = True
break
elif item.details["kind"] == "DirectoryContents":
if untracked and item.details["entry"]["status"] == "Untracked":
elif details["kind"] == "DirectoryContents":
if untracked and details["entry"]["status"] == "Untracked":
dirty = True
break
elif working_tree:
change = details.get("status", {})
if (
change.get("change") == "SubmoduleModification"
and not change["status"].state["superproject_configuration"]
):
raise _Unsupported("embedded repository diff policy (GIX-40)")
dirty = True
break
except _Unsupported as exc:
Expand Down
2 changes: 1 addition & 1 deletion gix-requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
GixPython==0.3.0 ; python_version >= "3.11"
GixPython==0.4.0 ; python_version >= "3.11"
2 changes: 1 addition & 1 deletion test-requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
coverage[toml]
GixPython==0.3.0 ; python_version >= "3.11"
GixPython==0.4.0 ; python_version >= "3.11"
basedpyright==1.39.9 ; python_version >= "3.9" and sys_platform != "cygwin"
ddt >= 1.1.1, != 1.4.3
mock # Also needed to typecheck the Python 3.7 import branches.
Expand Down
48 changes: 47 additions & 1 deletion test/test_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -703,9 +703,55 @@ def test_deserialization_reads_date_after_email(self):
)
if _backend.name == "gix":
for kind in ("commit", "tag"):
key = (kind + ".decode", "CLI: signature trailing fields (GIX-34)")
key = (kind + ".decode", "native")
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + 1)

def test_deserialization_preserves_email_whitespace(self):
with fixture_repo("commit.sh", "spaced-email") as repo:
root = Path(repo.working_dir).parent
oid = (root / "object-id").read_text().strip()
tag_oid = (root / "tag-id").read_text().strip()
self.assertEqual(repo.git.show("-s", "--format=[%ae][%ce]", oid), "[ a@example.com ][ c@example.com ]")
before = _backend.statistics()
commit = Commit(repo, bytes.fromhex(oid))
self.assertEqual((commit.author.email, commit.committer.email), (" a@example.com ", " c@example.com "))
self.assertEqual(TagObject(repo, bytes.fromhex(tag_oid)).tagger.email, " t@example.com ")
if _backend.name == "gix":
for key in (
("commit.decode", "CLI: signature identity differs from raw header (GIX-43)"),
("tag.decode", "native"),
):
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + 1)

def test_deserialization_negative_timestamp_matches_git(self):
with fixture_repo("commit.sh", "negative-date") as repo:
root = Path(repo.working_dir).parent
oid = (root / "object-id").read_text().strip()
tag_oid = (root / "tag-id").read_text().strip()
self.assertEqual(repo.git.show("-s", "--format=%ad", "--date=raw", oid), "")
before = _backend.statistics()
commit = Commit(repo, bytes.fromhex(oid))
self.assertEqual((commit.authored_date, commit.author_tz_offset), (0, 0))
self.assertEqual((commit.committed_date, commit.committer_tz_offset), (0, 0))
tag = TagObject(repo, bytes.fromhex(tag_oid))
self.assertEqual((tag.tagged_date, tag.tagger_tz_offset), (0, 0))
if _backend.name == "gix":
for kind in ("commit", "tag"):
key = (kind + ".decode", "CLI: negative signature timestamp (GIX-42)")
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + 1)

def test_deserialization_short_offset_matches_git(self):
with fixture_repo("commit.sh", "short-offset") as repo:
oid = (Path(repo.working_dir).parent / "object-id").read_text().strip()
self.assertEqual(repo.git.show("-s", "--format=%ad", "--date=raw", oid), "1112591163 +0020")
before = _backend.statistics()
commit = Commit(repo, bytes.fromhex(oid))
self.assertEqual((commit.authored_date, commit.author_tz_offset), (1112591163, -1200))
self.assertEqual((commit.committed_date, commit.committer_tz_offset), (1112591163, -1200))
if _backend.name == "gix":
key = ("commit.decode", "CLI: signature date differs from raw header (GIX-38)")
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + 1)

def test_deserialization_negative_zero_offset_stays_native(self):
with fixture_repo("commit.sh", "zero-offset") as repo:
root = Path(repo.working_dir).parent
Expand Down
54 changes: 53 additions & 1 deletion test/test_gix_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

import pytest

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


@pytest.mark.parametrize("object_format", ["sha1", "sha256"])
@pytest.mark.parametrize("entry_types", ["blob-and-link", "gitlink"])
def test_native_tree_entry_modes_match_git(object_format, entry_types):
with fixture_repo("tree-modes.sh", object_format, entry_types) as repo:
oid = (Path(repo.working_dir).parent / "tree-id").read_text().strip()
lines = repo.git.ls_tree(oid).splitlines()
expected = [(line.split("\t")[1], int(line.split()[0], 8)) for line in lines]
with patch.object(Git, "execute", side_effect=AssertionError("unexpected tree-listing CLI call")):
tree = Tree(repo, bytes.fromhex(oid), path="")
assert [(entry.path, entry.mode) for entry in tree] == expected


@pytest.mark.parametrize("object_format", ["sha1", "sha256"])
@pytest.mark.parametrize("entry_types", ["missing-mode", "zero-mode"])
def test_ambiguous_tree_entry_mode_uses_git(object_format, entry_types):
with fixture_repo("tree-modes.sh", object_format, entry_types) as repo:
oid = (Path(repo.working_dir).parent / "tree-id").read_text().strip()
tree = Tree(repo, bytes.fromhex(oid), path="")
before = _backend.statistics()
if entry_types == "missing-mode":
with pytest.raises(GitCommandError, match="malformed mode"):
repo.git.ls_tree(oid)
with pytest.raises(GitCommandError, match="malformed mode"):
list(tree)
else:
assert "160000 commit" in repo.git.ls_tree(oid)
assert tree["module"].mode == 0o160000
key = ("ls_tree", "CLI: ambiguous zero tree entry mode (GIX-41)")
assert _backend.statistics().get(key, 0) == before.get(key, 0) + 1


def test_native_metadata_paths_match_git_in_each_worktree(repo):
tmp_path = Path(repo.working_dir).parent
linked_path = tmp_path / "linked"
Expand Down Expand Up @@ -376,6 +407,17 @@ def snapshot():
assert snapshot() == expected


@pytest.mark.parametrize("object_format", ["sha1", "sha256"])
@pytest.mark.parametrize("syntax", ["implicit-extra", "inline-extra", "comment-in-key"])
def test_submodule_configuration_rejects_lines_git_rejects(object_format, syntax):
with fixture_repo("submodule-rejected-lines.sh", object_format, syntax) as repo:
with pytest.raises(GitCommandError, match="bad config line"):
repo.git.config("--file", ".gitmodules", "--list")
data = (Path(repo.working_dir) / ".gitmodules").read_bytes()
with pytest.raises(gix.Error):
gix.ModulesFile.from_bytes(data)


def test_native_revision_path_and_mode_match_cli(repo):
blob = repo.head.commit.tree["dir/file"]
revisions = ["HEAD:", "HEAD:dir/", "HEAD:dir/file", "HEAD:executable", "HEAD:link", ":executable", ":0:link"]
Expand Down Expand Up @@ -718,6 +760,16 @@ def test_native_status_tracks_submodule_dirtiness(repo):
assert dirty == [repo.is_dirty(**option) for option in options]


@pytest.mark.parametrize("target", ["untracked", "file"])
def test_embedded_status_uses_git_diff_policy(repo, target):
expected = target == "file"
assert bool(repo.git.diff("--raw")) == expected
before = _backend.statistics()
assert repo.is_dirty() == expected
key = ("Repo.is_dirty", "CLI: embedded repository diff policy (GIX-40)")
assert _backend.statistics().get(key, 0) == before.get(key, 0) + 1


@pytest.mark.parametrize("error", [OSError(22, "Invalid filename"), PermissionError(13, "Permission denied")])
def test_ignore_metadata_errors_retain_cli(error):
with fixture_repo("repo.sh", "ignore-verbatim") as repo:
Expand Down
11 changes: 10 additions & 1 deletion test/test_rev_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import pytest
from gitdb.exc import BadName

from git import Commit, Repo, GitCommandError
from git import Commit, Repo, GitCommandError, _backend
from test.lib.fixtures import fixture_repo, read_only_fixture


Expand Down Expand Up @@ -154,6 +154,15 @@ def test_rev_parse_reflog_selectors(rev_parse_repo):

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

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


def test_rev_parse_commit_message_search(rev_parse_repo):
repo = rev_parse_repo["repo"]
Expand Down
12 changes: 8 additions & 4 deletions tests/fixtures/commit.sh
Original file line number Diff line number Diff line change
Expand Up @@ -57,19 +57,23 @@ case "$1" in
raw)
git hash-object --literally -w -t commit "$2" > ../object-id
;;
trailing-date|zero-offset)
trailing-date|zero-offset|short-offset|negative-date|spaced-email)
date='1112591163 +0200 1700000000 -0500'
if [ "$1" = zero-offset ]; then date='1112591163 -0000'; fi
if [ "$1" = short-offset ]; then date='1112591163 +020'; fi
if [ "$1" = negative-date ]; then date='-1 +0200 1700000000 -0500'; fi
space=''
if [ "$1" = spaced-email ]; then space=' '; fi
tree=$(git mktree </dev/null)
{
printf 'tree %s\n' "$tree"
printf 'author A <a@example.com> %s\n' "$date"
printf 'committer C <c@example.com> %s\n' "$date"
printf 'author A <%sa@example.com%s> %s\n' "$space" "$space" "$date"
printf 'committer C <%sc@example.com%s> %s\n' "$space" "$space" "$date"
printf '\nmessage\n'
} | git hash-object --literally -w -t commit --stdin > ../object-id
{
printf 'object %s\ntype commit\ntag v1\n' "$(cat ../object-id)"
printf 'tagger T <t@example.com> %s\n' "$date"
printf 'tagger T <%st@example.com%s> %s\n' "$space" "$space" "$date"
printf '\nmessage\n'
} | git hash-object --literally -w -t tag --stdin > ../tag-id
git update-ref refs/tags/v1 "$(cat ../tag-id)"
Expand Down
10 changes: 10 additions & 0 deletions tests/fixtures/gix-backend.sh
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,16 @@ native_status_tracks_submodule_dirtiness)
git -C repo commit -qm 'add submodule'
printf modified > repo/module/file
;;
embedded_status_uses_git_diff_policy)
git init -q --object-format="$hash" repo/module
printf initial > repo/module/file
git -C repo/module add file
git -C repo/module commit -qm initial
oid=$(git -C repo/module rev-parse HEAD)
git -C repo update-index --add --cacheinfo "160000,$oid,module"
git -C repo commit -qm 'track embedded repository'
printf changed > "repo/module/$extra"
;;
native_commit_statistics_match_cli)
cd repo
git config diff.algorithm myers
Expand Down
12 changes: 12 additions & 0 deletions tests/fixtures/submodule-rejected-lines.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -eu
git init -q -b main --object-format="$1" repo
{
printf '[submodule "module"]\npath = module\nurl = ../base\n'
case "$2" in
implicit-extra) printf 'x url = ../other\n' ;;
inline-extra) printf '[submodule "module"] x url = ../other\n' ;;
comment-in-key) printf 'br#anch = main\n' ;;
*) exit 1 ;;
esac
} >repo/.gitmodules
19 changes: 19 additions & 0 deletions tests/fixtures/tree-modes.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -eu
git init -q -b main --object-format="$1" repo
git -C repo commit -qm initial --allow-empty
blob=$(printf data | git -C repo hash-object -w --stdin)
commit=$(git -C repo rev-parse HEAD)
write_entry () {
printf '%s %s\0' "$1" "$2"
printf '%b' "$(printf %s "$3" | sed 's/../\\x&/g')"
}
{
write_entry 100700 executable "$blob"
case "$2" in
gitlink) write_entry 140000 module "$commit" ;;
missing-mode) write_entry '' module "$commit" ;;
zero-mode) write_entry 0 module "$commit" ;;
esac
write_entry 120777 symlink "$blob"
} | git -C repo hash-object --literally -w -t tree --stdin >tree-id
Loading