diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 842695409..45e45e636 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -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 diff --git a/README.md b/README.md index 3776c2f43..92125b21d 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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. diff --git a/doc/gix-backend.md b/doc/gix-backend.md index 021279979..cc2ceae4c 100644 --- a/doc/gix-backend.md +++ b/doc/gix-backend.md @@ -3,7 +3,7 @@ This backend is unreleased. Install `.[gix]` from this checkout to make GitPython use GixPython for supported operations. GixPython is the distribution name; `gix` is its import name. The extra uses the official PyPI release -`GixPython==0.3.0` on CPython 3.11 or newer. On older Python versions, the +`GixPython==0.4.0` on CPython 3.11 or newer. On older Python versions, the dependency is omitted and GitPython uses the CLI backend. The ordinary GitPython installation still supports Python 3.8 or newer. @@ -16,11 +16,11 @@ uv pip install --python .tox/gix/bin/python --editable '.[test,gix]' `tox -e gix` also resolves the published GixPython release from the package index. -GixPython 0.3.0 publishes macOS wheels. On Windows and Linux, installation -builds the released source distribution and requires Rust 1.89 or newer and +GixPython 0.4.0 publishes macOS wheels. On Windows and Linux, installation +builds the released source distribution and requires Rust 1.95 or newer and a system linker. Its default build uses pure Rust hashing, compression and HTTPS; no C/C++ compiler is required for those dependencies. The release uses Gitoxide's -`gix` 0.90.0 and `gix-testtools` 0.22.0 from crates.io. The fixture suites for both +`gix` 0.91.0 and `gix-testtools` 0.23.0 from crates.io. The fixture suites for both backends need GixPython. CI prepares Rust for source builds and caches built wheels, Cargo dependencies and compilation output on the main matrix. @@ -53,6 +53,24 @@ provide general Git-path resolution. A `native` counter must represent a Gix-backed operation, and backend timings include its Python glue and any CLI fallbacks. +## GixPython 0.4.0 validation + +The published GixPython 0.4.0 macOS arm64 wheel reports Gitoxide +`541b4db0a59644b617a8b706b83af23e0b17f7f3`. The regression tests exercised it +with Git 2.54.0 in SHA-1 and SHA-256 repositories. + +- GIX-34 is fixed in 0.4.0. Structured author, committer and tagger + accessors return the first timezone after the email. The metadata adapter + accepts the native result when its date agrees with the stored header. +- GIX-35 is fixed for the three recorded malformed `.gitmodules` inputs. + `ModulesFile.from_bytes()` rejects each one, as Git does. +- GIX-36's gitlink classification is fixed. `TreeEntry.kind()` classifies + `140000` as a gitlink and identifies the executable and symlink correctly. + The adapter projects these native kinds to Git's listing modes. The raw + `TreeEntry.mode()` values still differ from Git's canonical display. +- GIX-37 still errors on a shallow object ID followed by a space. Git stops + the walk at that boundary. + ## Index and object metadata lifecycle `Repo(..., expand_vars=False)` accepts literal paths for callers such as sbxloop @@ -152,7 +170,7 @@ These read-only budgets make no claim that index editing is native. ## Install and test without package indexes -Prepare `.venv` and `.tox/gix` with GixPython 0.3.0. Select the backend explicitly +Prepare `.venv` and `.tox/gix` with GixPython 0.4.0. Select the backend explicitly when running against scripted fixtures: ```sh @@ -208,7 +226,7 @@ released source distribution and retain it in the wheelhouse. ## Scripted test fixtures -The `test` extra requires GixPython 0.3.0 on Python 3.11+. Full fixture suites +The `test` extra requires GixPython 0.4.0 on Python 3.11+. Full fixture suites run on Python 3.11 and newer with either backend. Python 3.8–3.10 retain installation/import smoke coverage, including the Cygwin Python 3.9 job. Running tests also requires Bash and Git 2.52+; `gix` here is GixPython's module. @@ -392,7 +410,7 @@ and predate the current fallback; they do not establish native coverage. | Selected `set_object` / reference deletion, `update_ref` | Native ref edits with GitPython's existing validation | Strict create/CAS, branch-target validation, symbolic aliases other than HEAD, symbolic detachment, active-branch HEAD log, unchanged targets and log-message cleanup; GIX-9/10/21/24 | | Tree/commit `Diffable.diff` | Raw change records and unambiguous exact renames | Patches, paths, index/worktree/root diff, inexact/ambiguous renames; GIX-11 | | `Commit.stats` | Native Myers line counts, binary counts, first-parent tree comparison | Diff attributes, other algorithms, gitlinks, non-ASCII or quoted filenames, large blobs; GIX-2/18 | -| `Repo.is_dirty` | Index/tree/worktree status, configured submodule checks and pathspecs | Custom/sparse indexes and non-root command directories | +| `Repo.is_dirty` | Index/tree/worktree status, configured submodule checks and pathspecs | Custom/sparse indexes, non-root command directories and embedded worktree changes (GIX-40) | | `Repo.untracked_files` | Native directory walk | Extra status options and non-root command directories | | `Repo.ignored` | Native excludes with tracked-file suppression | Symlink/submodule traversal, unsupported path normalization, and unavailable path metadata | @@ -989,10 +1007,16 @@ identify the historical fixture where needed. | GIX-31 | Bug (open) | GixPython 0.2.0 `Commit.decode()` rejects commit headers containing a CR-only or tab-only line with `object parsing failed, at gix-object/src/commit/decode.rs:20`. Git 2.54.0 accepts both objects with `fsck --strict`, continues through their header block and renders the later Latin-1 declaration and message correctly. A space-only continuation line decodes natively but retains the late encoding declaration in `extra_headers` (GIX-30). `test_deserialization_headers_end_at_empty_line` reproduces all three using the `commit.sh whitespace-headers` fixtures and checks Git's projection. | Accept Git-compatible header lines and end headers only at an empty line. The existing `object_metadata()` native decoder diagnostics fallback retains Git for CR/tab inputs; the existing GIX-30 fallback covers the space input. Neither fallback closes these bugs. | | GIX-32 | Missing capability (open); no demonstrated Git compatibility mismatch | Windows CI on GixPython 0.3.0, Git 2.56.0.windows.2 and CPython 3.12.10 enumerates the non-UTF-8 packed names in `legacy-refs.sh`, but exact byte-name lookup selects `Reference.read: CLI: native read diagnostics`; the no-CLI guard fails for SHA-1 and SHA-256. POSIX lookup succeeds. Git's Windows CLI likewise cannot address those original bytes through UTF-16 arguments, so there is no demonstrated equivalent Windows CLI operand. Git enumeration does preserve both names. | Provide native Windows packed-reference lookup for byte names without first converting the name to a loose-reference filesystem path. Keep `reference_info()`'s existing diagnostic fallback; `test_non_utf8_tag_names_preserve_bytes` checks it on Windows. Resolution coverage and native claims remain POSIX-only. The upstream lookup source attempts loose-path conversion before consulting packed refs; CI demonstrates the fallback, but does not capture the underlying Gix error text. | | GIX-33 | Bug (open); missing exact-name mode | With Git 2.54.0 and GixPython 0.3.0, `exact-refs.sh sha1 files symbolic` makes `refs/tags/REBASE_HEAD` a symbolic ref to another tag while the root `REBASE_HEAD` is absent. `Repository.try_find_reference("REBASE_HEAD")` returns that tag; native `_symbolic_ref` formerly returned its target, whereas `git symbolic-ref --quiet --no-recurse -- REBASE_HEAD` exits 1. GitPython's root-reference object read consequently returned a commit through Gix and raised `ValueError` through CLI. SHA-256 reproduces the same mismatch. | Expose an exact-name lookup mode, including root references, whose absence and error behavior matches Git. `_symbolic_ref()` compares the native reference's name with the requested bytes and selects CLI for a lookalike. `test_missing_root_reference_does_not_follow_symbolic_lookalike_tag` verifies parity and forced CLI fallback. This adapter guard does not close the upstream compatibility bug. | -| GIX-34 | Bug (open) | With Git 2.54.0 and GixPython 0.3.0, an author, committer or tagger line with fields after its time zone, such as `A 1112591163 +0200 1700000000 -0500`, decodes through `Commit.author()`/`committer()` and `Tag.tagger()` with the correct seconds but an offset of 0. Git reads only the first date and time zone after the last `>` (`split_ident_line`) and reports `1112591163 +0200` through `git show --format=%ad --date=raw` and `%(taggerdate:raw)`. `git fsck` reports `badTimezone` for such objects, but the default `transfer.fsckObjects=false` accepts them. The `trailing-date` read-only `commit.sh` fixture in `test_deserialization_reads_date_after_email` reproduces both object kinds. | Report the time zone Git reads for identity lines with trailing fields, or reject them consistently. `object_metadata()` selects CLI when the decoded signature does not reproduce the end of its raw header line. This adapter guard does not close the upstream compatibility bug. | -| GIX-35 | Bug (open) | With Git 2.54.0 and GixPython 0.3.0, `ModulesFile.from_bytes()` accepts `.gitmodules` lines that Git rejects with `bad config line`, so `git submodule update --init` stops while `git fsck` reports only `gitmodulesParse`. A line holding more than one name is read as several settings: after `url = ../good`, `x url = ../evil` makes `url()` return `../evil` with `submodule..x` true, and `[submodule "module"] x url = ../evil` does the same on the header line. `br#anch = main` is read as an implicit `br` followed by a comment. The `submodule-rejected-lines.sh` read-only fixture in `test_submodule_configuration_rejects_lines_git_rejects` reproduces all three. | Reject the lines Git rejects, at least in a Git-strict parsing mode, with a typed error. `submodule_config()` selects CLI unless every line is blank, a comment, a bare submodule header or a single `key` or `key = value` setting, so Git's parser reports the error. This adapter guard does not close the upstream compatibility bug. | -| GIX-36 | Bug (open) | With Git 2.54.0 and GixPython 0.3.0, `Tree.iter()` reports tree entry modes as stored, while Git canonicalizes them when it reads a tree (`canon_mode`): `git ls-tree` and checkout use `100755` for `100700`, `120000` for `120777` and `160000` for every mode whose type is not a regular file, symbolic link or directory. `TreeEntry.mode()` returned `0o100700` and `0o120777`, so `Blob.mode` did not match `Blob.executable_mode` or `Blob.link_mode` for entries Git checks out as an executable or a symbolic link. A `140000` entry, which Git reads as a gitlink, is reported as a tree with mode `0o40000`, so GitPython listed the contents of an object Git never checks out; other noncanonical gitlink modes made tree iteration raise `TypeError`. `git fsck` reports these trees only as `badFilemode` warnings, so default transfers accept them. The `tree-modes.sh` read-only fixture in `test_tree_entry_modes_match_git` reproduces all three for SHA-1 and SHA-256. | Report the modes Git reads, at least in a Git-compatible mode, or expose the raw mode bytes. `_ls_tree()` selects CLI unless every native mode is one Git reports and the tree's bytes re-encode to the same object ID through the in-memory object database, so Git lists the entries. This adapter guard does not close the upstream compatibility bug. | -| GIX-37 | Bug (open) | On macOS with Git 2.54.0 and GixPython 0.3.0, create a linear history `A <- B <- C` with `HEAD` at `C` and write `B`'s full SHA-1 followed by a space and newline to `.git/shallow`. `git rev-list --skip=1 HEAD` returns only `B` and stops at the shallow boundary. `Repository.rev_walk([repo.head_id()]).all()` instead raises a `gix.Error` when consumed: `gix-shallow` treats the trailing space as a 41st hexadecimal character. | Match Git's shallow-file parsing in Gitoxide. `Commit.iter_parents(first_parent=False)` keeps the existing CLI fallback in `_backend.history()` and returns `B` with or without `max_count=1`. An explicitly native `first_parent=True` walk still exposes the parsing mismatch, which also occurs through `Commit.iter_items(..., first_parent=True, skip=1)`. | +| GIX-34 | Fixed in Gitoxide 0.91.0 | With Git 2.54.0 and GixPython 0.3.0, an author, committer or tagger line with fields after its time zone, such as `A 1112591163 +0200 1700000000 -0500`, decodes through `Commit.author()`/`committer()` and `Tag.tagger()` with the correct seconds but an offset of 0. Git reads only the first date and time zone after the last `>` (`split_ident_line`) and reports `1112591163 +0200` through `git show --format=%ad --date=raw` and `%(taggerdate:raw)`. `git fsck` reports `badTimezone` for such objects, but the default `transfer.fsckObjects=false` accepts them. The `trailing-date` read-only `commit.sh` fixture in `test_deserialization_reads_date_after_email` reproduces both object kinds. | Gitoxide fixed the offset in `39e523a8ce`. The GixPython 0.4.0 wheel passes both native decoding checks. The adapter retains its date validation for GIX-38. | +| GIX-35 | Fixed in Gitoxide 0.91.0 | With Git 2.54.0 and GixPython 0.3.0, `ModulesFile.from_bytes()` accepts `.gitmodules` lines that Git rejects with `bad config line`, so `git submodule update --init` stops while `git fsck` reports only `gitmodulesParse`. A line holding more than one name is read as several settings: after `url = ../good`, `x url = ../evil` makes `url()` return `../evil` with `submodule..x` true, and `[submodule "module"] x url = ../evil` does the same on the header line. `br#anch = main` is read as an implicit `br` followed by a comment. The `submodule-rejected-lines.sh` read-only fixture in `test_submodule_configuration_rejects_lines_git_rejects` reproduces all three. | Gitoxide rejects all three inputs after the parser change in `3d3aa94b70`. The GixPython 0.4.0 wheel passes the regression on both object formats. GitPython retains its existing fallback for native parse errors. | +| GIX-36 | Classification fixed in Gitoxide 0.91.0; raw mode mismatch open | With Git 2.54.0 and GixPython 0.3.0, `Tree.iter()` reports tree entry modes as stored, while Git canonicalizes them when it reads a tree (`canon_mode`): `git ls-tree` and checkout use `100755` for `100700`, `120000` for `120777` and `160000` for every mode whose type is not a regular file, symbolic link or directory. `TreeEntry.mode()` returned `0o100700` and `0o120777`, so `Blob.mode` did not match `Blob.executable_mode` or `Blob.link_mode` for entries Git checks out as an executable or a symbolic link. A `140000` entry, which Git reads as a gitlink, is reported as a tree with mode `0o40000`, so GitPython listed the contents of an object Git never checks out; other noncanonical gitlink modes made tree iteration raise `TypeError`. `git fsck` reports these trees only as `badFilemode` warnings, so default transfers accept them. The `tree-modes.sh` read-only fixture reproduces all three for SHA-1 and SHA-256. | Gitoxide preserves the raw mode and fixes classification in `74a7a86060`. `_ls_tree()` formats the native kinds as Git listing modes. `test_native_tree_entry_modes_match_git` verifies the listing against Git on the GixPython 0.4.0 wheel. The raw-mode mismatch remains open. Expose Git's canonical mode as a separate native projection. | +| GIX-37 | Bug (open) | On macOS with Git 2.54.0 and GixPython 0.3.0 or 0.4.0, create a linear history `A <- B <- C` with `HEAD` at `C` and write `B`'s full SHA-1 followed by a space and newline to `.git/shallow`. `git rev-list --skip=1 HEAD` returns only `B` and stops at the shallow boundary. `Repository.rev_walk([repo.head_id()]).all()` instead raises a `gix.Error` when consumed: `gix-shallow` treats the trailing space as a 41st hexadecimal character. | Match Git's shallow-file parsing in Gitoxide. `Commit.iter_parents(first_parent=False)` keeps the existing CLI fallback in `_backend.history()` and returns `B` with or without `max_count=1`. An explicitly native `first_parent=True` walk still exposes the parsing mismatch, which also occurs through `Commit.iter_items(..., first_parent=True, skip=1)`. | +| GIX-38 | Bug (open) | With Git 2.54.0 and GixPython 0.4.0, the `commit.sh short-offset` fixture stores `1112591163 +020` in an identity. `git show -s --format=%ad --date=raw` reports `1112591163 +0020`, while `Commit.author()` reports an offset of zero. A separate probe with `+0299` preserves that spelling in Git but renders as `+0339` from the native offset in seconds. | Expose Git-compatible interpretation of short offsets and a way to preserve the stored offset spelling. `object_metadata()` accepts native dates when their formatted prefix matches the raw identity and otherwise keeps the existing CLI fallback. `test_deserialization_short_offset_matches_git` verifies the fallback returns the 20-minute offset. | +| GIX-39 | Bug (open) | On Git 2.54.0, `git rev-parse --verify HEAD@{never}` rejects the date. GixPython 0.4.0's `Repository.rev_parse_single()` returns the oldest commit. With reflog entries 80, 52, 49, 40, 3 and 0 hours old, Git also selects the 80-hour entry for `HEAD@{2days3hours}`, while Gix selects the 52-hour entry. | Match Git's approxidate grammar and invalid-date handling. `_check_revision_grammar()` retains CLI for textual selectors. `test_rev_parse_reflog_selectors` covers a rejected date, an accepted date and ordinary reflog selectors. | +| GIX-40 | Bug (open) | With Git 2.54.0 and GixPython 0.4.0, `gix-backend.sh embedded_status_uses_git_diff_policy` tracks a gitlink without a `.gitmodules` entry. An untracked file in its checkout leaves `git diff --raw` empty, but native configured status reports a `SubmoduleModification` with `superproject_configuration` false. Both report changes to tracked files in the embedded checkout. The fixture covers SHA-1 and SHA-256. | Expose Git's diff ignore policy for embedded repositories. `Repo.is_dirty()` uses Git when native worktree status reports a modification in an embedded repository. | +| GIX-41 | Bug (open) | With Git 2.54.0 and GixPython 0.4.0, `tree-modes.sh` writes an entry with either an empty mode field or the literal `0`. Both are decoded by `Tree.iter()` as mode zero and kind `commit`. Git rejects the empty field with `malformed mode in tree entry` and lists the literal zero as a gitlink. `test_ambiguous_tree_entry_mode_uses_git` verifies both results for SHA-1 and SHA-256. | Reject a missing mode or expose the distinction between a missing mode and an encoded zero. `_ls_tree()` defers mode zero to Git for validation and formatting. | +| GIX-42 | Bug (open) | With Git 2.54.0 and GixPython 0.4.0, `commit.sh negative-date` stores `-1 +0200 1700000000 -0500` in the author, committer and tagger identities. Git's `split_ident_line()` requires unsigned timestamp digits, so `git show --format=%ad --date=raw` reports no date and GitPython's CLI path returns `(0, 0)`. Native signature accessors expose `(-1, +7200)` as seconds and offset east of UTC. | Provide Git-compatible negative timestamp handling. `object_metadata()` retains CLI for negative dates. `test_deserialization_negative_timestamp_matches_git` verifies both object kinds. | +| GIX-43 | Bug (open) | With Git 2.54.0 and GixPython 0.4.0, `commit.sh spaced-email` stores spaces inside the email brackets ahead of a date with trailing fields. Git's `%ae` and `%ce` preserve these bytes, but native commit author and committer accessors trim them. The native tagger accessor preserves the spaces. | Expose a signature identity that preserves the stored fields with Git-compatible delimiters. `object_metadata()` uses the existing CLI fallback if the native identity fails the raw header comparison. `test_deserialization_preserves_email_whitespace` verifies author, committer and tagger properties. | GIX-14 also covers configured worktree symlink resolution. On macOS with GixPython 0.3.0, CPython 3.12.14 and Git 2.54.0, set a submodule's diff --git a/git/_backend.py b/git/_backend.py index 51d25c436..21ba1393f 100644 --- a/git/_backend.py +++ b/git/_backend.py @@ -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)") 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: 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: @@ -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: @@ -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: diff --git a/gix-requirements.txt b/gix-requirements.txt index 4e85a92c7..5e1ec6fe6 100644 --- a/gix-requirements.txt +++ b/gix-requirements.txt @@ -1 +1 @@ -GixPython==0.3.0 ; python_version >= "3.11" +GixPython==0.4.0 ; python_version >= "3.11" diff --git a/test-requirements.txt b/test-requirements.txt index aa357c2ae..e185ca58f 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -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. diff --git a/test/test_commit.py b/test/test_commit.py index ef421b66b..5a7e0ca71 100644 --- a/test/test_commit.py +++ b/test/test_commit.py @@ -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 diff --git a/test/test_gix_backend.py b/test/test_gix_backend.py index 80c15c294..e5045d5ae 100644 --- a/test/test_gix_backend.py +++ b/test/test_gix_backend.py @@ -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 @@ -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" @@ -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"] @@ -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: diff --git a/test/test_rev_parse.py b/test/test_rev_parse.py index d86fe832d..8d7d6b527 100644 --- a/test/test_rev_parse.py +++ b/test/test_rev_parse.py @@ -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 @@ -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"] diff --git a/tests/fixtures/commit.sh b/tests/fixtures/commit.sh index ec6de256e..19ca72903 100644 --- a/tests/fixtures/commit.sh +++ b/tests/fixtures/commit.sh @@ -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 %s\n' "$date" - printf 'committer C %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 %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)" diff --git a/tests/fixtures/gix-backend.sh b/tests/fixtures/gix-backend.sh index d90d3f4ab..5325b7dbb 100644 --- a/tests/fixtures/gix-backend.sh +++ b/tests/fixtures/gix-backend.sh @@ -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 diff --git a/tests/fixtures/submodule-rejected-lines.sh b/tests/fixtures/submodule-rejected-lines.sh new file mode 100755 index 000000000..02740d742 --- /dev/null +++ b/tests/fixtures/submodule-rejected-lines.sh @@ -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 diff --git a/tests/fixtures/tree-modes.sh b/tests/fixtures/tree-modes.sh new file mode 100755 index 000000000..c8277d410 --- /dev/null +++ b/tests/fixtures/tree-modes.sh @@ -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