Skip to content

Commit 5dc5c76

Browse files
authored
Merge pull request #2355 from JROtto5/fix/iter-parents-skip
fix(commit): don't skip a parent when `iter_parents` filters out self
2 parents f961374 + 58e336e commit 5dc5c76

4 files changed

Lines changed: 110 additions & 9 deletions

File tree

‎doc/gix-backend.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -992,6 +992,7 @@ identify the historical fixture where needed.
992992
| 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 <a@example.com> 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. |
993993
| 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.<name>.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. |
994994
| 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. |
995+
| 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)`. |
995996

996997
GIX-14 also covers configured worktree symlink resolution. On macOS with
997998
GixPython 0.3.0, CPython 3.12.14 and Git 2.54.0, set a submodule's

‎git/objects/commit.py‎

Lines changed: 58 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55

66
__all__ = ["Commit"]
77

8-
from collections import defaultdict
8+
from collections import defaultdict, deque
99
import datetime
1010
from io import BytesIO
11+
from itertools import chain, islice
1112
import logging
1213
import os
1314
from subprocess import Popen
@@ -36,6 +37,7 @@
3637

3738
from typing import (
3839
Any,
40+
Deque,
3941
Dict,
4042
IO,
4143
Iterator,
@@ -480,18 +482,66 @@ def iter_parents(self, paths: Union[PathLike, Sequence[PathLike]] = "", **kwargs
480482
contain at least one of the paths.
481483
482484
:param kwargs:
483-
All arguments allowed by :manpage:`git-rev-list(1)`.
485+
All arguments allowed by :manpage:`git-rev-list(1)`. ``skip`` values of
486+
0 and 1 skip only ``self``; larger values also skip matching ancestors.
484487
485488
:return:
486489
Iterator yielding :class:`Commit` objects which are parents of ``self``
487490
"""
488-
# skip ourselves
489-
skip = kwargs.get("skip", 1)
490-
if skip == 0: # skip ourselves
491-
skip = 1
492-
kwargs["skip"] = skip
491+
skip = max(0, int(kwargs.pop("skip", None) or 1) - 1)
492+
count_options = {"max_count", "max-count", "n"}
493+
if not paths and kwargs.keys() <= count_options:
494+
return self.iter_items(self.repo, self, paths, skip=skip + 1, **kwargs)
495+
496+
# Keep Git's option order when resolving alternate spellings of max_count.
497+
limits = {key: kwargs.pop(key) for key in tuple(kwargs) if key in count_options}
498+
count_args = self.repo.git.transform_kwargs(**limits) if limits else []
499+
max_count = int(count_args[-1].rsplit("=", 1)[-1]) if count_args else -1
500+
if max_count == 0:
501+
return self.iter_items(self.repo, self, paths, max_count=0, **kwargs)
502+
503+
reverse_args = self.repo.git.transform_kwargs(reverse=kwargs["reverse"]) if "reverse" in kwargs else []
504+
reverse = bool(reverse_args) and all(arg == "--reverse" for arg in reverse_args)
505+
if reverse and max_count < 0:
506+
commits = self.iter_items(self.repo, self, paths, **kwargs)
507+
508+
def skip_from_end() -> Iterator["Commit"]:
509+
# Git applies skip before reversing. Hold back just the commits that
510+
# might need to be skipped, including self if it is last.
511+
tail: Deque[Commit] = deque()
512+
for commit in commits:
513+
tail.append(commit)
514+
if len(tail) > skip + 1:
515+
yield tail.popleft()
516+
if len(tail) == skip + 1 and tail[-1] != self:
517+
yield tail[0]
518+
519+
return skip_from_end()
520+
521+
if reverse:
522+
del kwargs["reverse"]
523+
if max_count > 0:
524+
# Allow room for self even though filters may leave it out.
525+
kwargs["max_count"] = skip + max_count + 1
526+
commits = self.iter_items(self.repo, self, paths, **kwargs)
527+
528+
def skip_from_start() -> Iterator["Commit"]:
529+
first = next(commits, None)
530+
if first is None:
531+
return
532+
start = skip + (first == self)
533+
stop = start + max_count if max_count > 0 else None
534+
parents = islice(chain((first,), commits), start, stop)
535+
if reverse:
536+
yield from reversed(list(parents))
537+
else:
538+
yield from parents
539+
if stop is not None:
540+
# Finish the walk, consuming the one extra result if self was filtered out.
541+
for _ in commits:
542+
pass
493543

494-
return self.iter_items(self.repo, self, paths, **kwargs)
544+
return skip_from_start()
495545

496546
@property
497547
def stats(self) -> Stats:

‎test/test_commit.py‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import os.path as osp
1212
import sys
1313
import time
14-
from unittest.mock import Mock
14+
from unittest.mock import Mock, patch
1515

1616
from gitdb import IStream
1717

@@ -476,6 +476,46 @@ def test_iter_parents(self):
476476
self.assertEqual(first_parent, c.parents[0])
477477
# END for each
478478

479+
def test_iter_parents_when_self_is_filtered_out(self):
480+
with fixture_repo("commit.sh", "iter-parents") as repo:
481+
tip, merge = repo.commit("B"), repo.commit("M")
482+
a1, a2 = repo.commit("A1"), repo.commit("A2")
483+
for skip in (0, 1):
484+
self.assertEqual(list(tip.iter_parents(paths="a", skip=skip)), [a2, a1])
485+
self.assertEqual(list(tip.iter_parents(paths="a", skip=2)), [a1])
486+
self.assertEqual(list(tip.iter_parents(paths="a", skip="2")), [a1])
487+
self.assertEqual(list(tip.iter_parents(paths="a", skip=None)), [a2, a1])
488+
self.assertEqual(list(tip.iter_parents(paths="a", max_count=1)), [a2])
489+
self.assertEqual(list(tip.iter_parents(paths="a", reverse=True)), [a1, a2])
490+
self.assertEqual(list(merge.iter_parents(paths="a", first_parent=True)), [a2, a1])
491+
self.assertEqual(list(merge.iter_parents(grep="^A")), [a2, a1])
492+
# Commits that do match keep the old meaning of skip.
493+
self.assertEqual(list(a2.iter_parents(paths="a")), [a1])
494+
self.assertEqual(list(tip.iter_parents(paths="b")), [])
495+
496+
def test_iter_parents_uses_one_walk(self):
497+
with fixture_repo("commit.sh", "iter-parents") as repo:
498+
tip, a1, a2 = repo.commit("B"), repo.commit("A1"), repo.commit("A2")
499+
with patch.object(Commit, "iter_items", wraps=Commit.iter_items) as iter_items:
500+
self.assertEqual(list(tip.iter_parents(paths="a", max_count=1)), [a2])
501+
self.assertEqual(iter_items.call_count, 1)
502+
503+
self.assertEqual(list(tip.iter_parents(paths="a", max_count=0)), [])
504+
self.assertEqual(list(tip.iter_parents(paths="a", n=1)), [a2])
505+
self.assertEqual(list(a2.iter_parents(paths="a", max_count=1)), [a1])
506+
self.assertEqual(list(a2.iter_parents(paths="a", skip=None)), [a1])
507+
508+
def test_iter_parents_reverses_after_applying_limits(self):
509+
with fixture_repo("commit.sh", "iter-parents") as repo:
510+
tip, a1, a2 = repo.commit("B"), repo.commit("A1"), repo.commit("A2")
511+
self.assertEqual(list(tip.iter_parents(paths="a", reverse=True, max_count=1)), [a2])
512+
self.assertEqual(list(tip.iter_parents(paths="a", reverse=True, skip=2, max_count=1)), [a1])
513+
self.assertEqual(list(tip.iter_parents(paths="a", reverse=True, skip=2)), [a1])
514+
self.assertEqual(list(tip.iter_parents(paths="a", reverse=True, skip=3)), [])
515+
self.assertEqual(list(a2.iter_parents(paths="a", reverse=True, max_count=1)), [a1])
516+
self.assertEqual(list(a2.iter_parents(paths="a", reverse=True)), [a1])
517+
self.assertEqual(list(a2.iter_parents(paths="a", reverse=True, skip=2)), [])
518+
479519
def test_name_rev(self):
480520
name_rev = self.rorepo.head.commit.name_rev
481521
assert isinstance(name_rev, str)

‎tests/fixtures/commit.sh‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,16 @@ case "$1" in
3333
git tag removed "$commit"
3434
git update-ref refs/heads/master "$commit"
3535
;;
36+
iter-parents)
37+
# A merge whose other side and own commit both leave `a` alone.
38+
echo 1 > a && git add a && git commit -m A1 && git tag A1
39+
echo 2 > a && git add a && git commit -m A2 && git tag A2
40+
git checkout -b side A1
41+
echo s > s && git add s && git commit -m S
42+
git checkout master
43+
git merge --no-ff -m M side && git tag M
44+
echo x > b && git add b && git commit -m B && git tag B
45+
;;
3646
ambiguous)
3747
touch master
3848
git add master

0 commit comments

Comments
 (0)