From 6ddc49c687928e24367ef2b7c2ee79c6a21aff7e Mon Sep 17 00:00:00 2001 From: JROtto5 <222316562+JROtto5@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:15:23 -0500 Subject: [PATCH 1/9] fix(remote): keep push results for sources that are not refs `git push --porcelain` prints the source side of each refspec as it was given, so `git push origin :refs/heads/x` or `HEAD~1:refs/heads/x` reports `` or `HEAD~1` there. `PushInfo._from_line()` passed it to `Reference.from_path()`, which raised `ValueError`, and `_get_push_info()` dropped the line. A push of only such sources returned an empty list, and a mixed push only the results for the other refspecs. When the source is not a reference, set `local_ref` to `None`, as it already is for deletes, and record the pushed object's hash in a new `local_hash` attribute. This is the shape suggested in #1624. The hash comes from git's `old..new` summary when there is one, because the push can move a ref the source is relative to, such as `origin/main~1`; only new refs and rejected lines resolve the source. `test_push_revision_sources` pushes a hash, `HEAD~1` and `HEAD` in one call, then force-pushes `self/pushed_ref~1` over the ref it is relative to. It fails without this change under the `cli` and `gix` backends, and passes with it. Agent-Model: claude-opus-5-5 --- doc/source/changes.rst | 3 +++ git/remote.py | 37 ++++++++++++++++++++++++++++--------- test/test_remote.py | 27 +++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 9 deletions(-) diff --git a/doc/source/changes.rst b/doc/source/changes.rst index e264c8056..c58020c99 100644 --- a/doc/source/changes.rst +++ b/doc/source/changes.rst @@ -115,6 +115,9 @@ API changes current repository (``branch..remote=.``) as the upstream, instead of constructing an invalid ``refs/remotes/./...`` reference. Git resolves the upstream location; remote tracking branches retain their existing behavior. +* ``Remote.push()`` no longer drops results whose source is not a reference, + such as a commit hash or ``HEAD~1``. Their ``PushInfo.local_ref`` is ``None``, + and the new ``PushInfo.local_hash`` holds the hash of the pushed object. * ``GitCmdObjectDB`` no longer inherits ``LooseObjectDB``. Its object reads, writes, existence checks, and enumeration use Git, including packed objects. Precompressed input streams and custom object-output writers are unsupported. diff --git a/git/remote.py b/git/remote.py index 4b470b5f0..7a43fe563 100644 --- a/git/remote.py +++ b/git/remote.py @@ -32,6 +32,7 @@ from git.cmd import Git, handle_process_output from git.compat import force_text from git.config import GitConfigParser, SectionConstraint, cp +from git.exc import BadName from git.refs import Reference, RemoteReference, SymbolicReference, TagReference from git.types import AnyGitObject, Literal, PathLike from git.util import ( @@ -121,7 +122,11 @@ class PushInfo(IterableObj): info = remote.push()[0] info.flags # bitflags providing more information about the result info.local_ref # Reference pointing to the local reference that was pushed - # It is None if the ref was deleted. + # It is None if the ref was deleted, or if the pushed source + # was not a reference, like a commit hash or HEAD~1. + info.local_hash # Hash of the pushed object if the source was not a + # reference, otherwise None. For new and rejected refs git + # prints no hash, so the source is resolved after the push. info.remote_ref_string # path to the remote reference located on the remote side info.remote_ref # Remote Reference on the local side corresponding to # the remote_ref_string. It can be a TagReference as well. @@ -132,6 +137,7 @@ class PushInfo(IterableObj): __slots__ = ( "local_ref", + "local_hash", "remote_ref_string", "flags", "_old_commit_sha", @@ -173,6 +179,7 @@ def __init__( remote: "Remote", old_commit: Optional[str] = None, summary: str = "", + local_hash: Optional[str] = None, ) -> None: """Initialize a new instance. @@ -180,6 +187,7 @@ def __init__( """ self.flags = flags self.local_ref = local_ref + self.local_hash = local_hash self.remote_ref_string = remote_ref_string self._remote = remote self._old_commit_sha = old_commit @@ -226,16 +234,18 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo": # from_to handling from_ref_string, to_ref_string = from_to.split(":") - if flags & cls.DELETED: - from_ref: Union[SymbolicReference, None] = None - else: - if from_ref_string == "(delete)": - from_ref = None - else: + from_ref: Union[SymbolicReference, None] = None + is_revision = False + if not flags & cls.DELETED and from_ref_string != "(delete)": + try: from_ref = Reference.from_path(remote.repo, from_ref_string) + except ValueError: + # Git prints the source as it was given, which can be any revision. + is_revision = True # Commit handling, could be message or commit info old_commit: Optional[str] = None + new_sha: Optional[str] = None if summary.startswith("["): if "[rejected]" in summary: flags |= cls.REJECTED @@ -256,12 +266,21 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo": split_token = "..." if control_character == " ": split_token = ".." - old_sha, _new_sha = summary.split(" ")[0].split(split_token) + old_sha, new_sha = summary.split(" ")[0].split(split_token) # Have to use constructor here as the sha usually is abbreviated. old_commit = old_sha # END message handling - return PushInfo(flags, from_ref, to_ref_string, remote, old_commit, summary) + local_hash: Optional[str] = None + if is_revision: + # The push may have moved a ref the revision is relative to, like + # origin/main~1, so prefer the hash git reports as pushed. + try: + local_hash = remote.repo.rev_parse(new_sha or from_ref_string).hexsha + except BadName: + pass + + return PushInfo(flags, from_ref, to_ref_string, remote, old_commit, summary, local_hash) @classmethod def iter_items(cls, repo: "Repo", *args: Any, **kwargs: Any) -> NoReturn: # -> Iterator['PushInfo']: diff --git a/test/test_remote.py b/test/test_remote.py index ba18dce3a..e1c6c9c83 100644 --- a/test/test_remote.py +++ b/test/test_remote.py @@ -554,6 +554,33 @@ def test_fetch_prune_skips_deleted_refs(self, rw_repo): "pruned refs are skipped without a warning", ) + @with_rw_repo("HEAD", bare=False) + def test_push_revision_sources(self, rw_repo): + remote = rw_repo.create_remote("self", rw_repo.git_dir) + parent = rw_repo.head.commit.parents[0] + res = remote.push( + [ + "%s:refs/heads/pushed_hash" % parent.hexsha, + "HEAD~1:refs/heads/pushed_rev", + "HEAD:refs/heads/pushed_ref", + ] + ) + infos = {info.remote_ref_string: info for info in res} + self.assertEqual(set(infos), {"refs/heads/pushed_hash", "refs/heads/pushed_rev", "refs/heads/pushed_ref"}) + for name in ("refs/heads/pushed_hash", "refs/heads/pushed_rev"): + self.assertTrue(infos[name].flags & PushInfo.NEW_HEAD) + self.assertIsNone(infos[name].local_ref) + self.assertEqual(infos[name].local_hash, parent.hexsha) + self.assertEqual(infos["refs/heads/pushed_ref"].local_ref, rw_repo.head) + self.assertIsNone(infos["refs/heads/pushed_ref"].local_hash) + + # The push moves self/pushed_ref, which the source is relative to. + remote.fetch() + (info,) = remote.push("self/pushed_ref~1:refs/heads/pushed_ref", force=True) + self.assertTrue(info.flags & PushInfo.FORCED_UPDATE) + self.assertIsNone(info.local_ref) + self.assertEqual(info.local_hash, parent.hexsha) + @with_rw_repo("HEAD", bare=True) def test_creation_and_removal(self, bare_rw_repo): new_name = "test_new_one" From c8aa12fffd4cc6f7cb2218a9ea3b7357618cb7e1 Mon Sep 17 00:00:00 2001 From: JROtto5 <222316562+JROtto5@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:39:14 -0500 Subject: [PATCH 2/9] fix(remote): harden push source lookup for revision sources Three gaps in the non-ref source handling, from review: - `Reference.from_path()` accepts any `refs/` path, so a source such as `refs/heads/main~1` became a `Head` that does not exist. Sources with `~`, `^` or `@{`, which `check-ref-format` never allows in a ref name, are now taken as revisions without trying `from_path()`. - `rev-parse` prefers a ref over an object ID with the same spelling, so a branch named like the abbreviated ID in git's summary gave the wrong `local_hash`. Expand it with `rev-parse --disambiguate`, which only looks at object IDs. - A lookup error other than `BadName` escaped the stdout handler and dropped the push result. Keep the result with `local_hash=None`. `test_push_revision_sources` covers each case, including a failing lookup on both paths; each new assertion fails with only its part of the change reverted, under `cli` and `gix`. Agent-Model: claude-opus-5-5 --- git/remote.py | 26 +++++++++++++++++++------- test/test_remote.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 7 deletions(-) diff --git a/git/remote.py b/git/remote.py index 7a43fe563..0eba7d093 100644 --- a/git/remote.py +++ b/git/remote.py @@ -32,7 +32,7 @@ from git.cmd import Git, handle_process_output from git.compat import force_text from git.config import GitConfigParser, SectionConstraint, cp -from git.exc import BadName +from git.exc import GitCommandError, ODBError from git.refs import Reference, RemoteReference, SymbolicReference, TagReference from git.types import AnyGitObject, Literal, PathLike from git.util import ( @@ -171,6 +171,9 @@ class PushInfo(IterableObj): "!": ERROR, } + # git check-ref-format rejects these in ref names; revisions use them. + _re_revision_syntax = re.compile(r"[~^]|@\{") + def __init__( self, flags: int, @@ -237,11 +240,15 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo": from_ref: Union[SymbolicReference, None] = None is_revision = False if not flags & cls.DELETED and from_ref_string != "(delete)": - try: - from_ref = Reference.from_path(remote.repo, from_ref_string) - except ValueError: - # Git prints the source as it was given, which can be any revision. + # Git prints the source as it was given, which can be any revision. + # from_path() would accept one under refs/, like refs/heads/main~1. + if cls._re_revision_syntax.search(from_ref_string): is_revision = True + else: + try: + from_ref = Reference.from_path(remote.repo, from_ref_string) + except ValueError: + is_revision = True # Commit handling, could be message or commit info old_commit: Optional[str] = None @@ -276,8 +283,13 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo": # The push may have moved a ref the revision is relative to, like # origin/main~1, so prefer the hash git reports as pushed. try: - local_hash = remote.repo.rev_parse(new_sha or from_ref_string).hexsha - except BadName: + if new_sha: + # rev-parse would prefer a ref spelled like the abbreviated ID. + oids = remote.repo.git._call_process_safe("rev_parse", "--disambiguate=%s" % new_sha).split() + local_hash = oids[0] if len(oids) == 1 else None + else: + local_hash = remote.repo.rev_parse(from_ref_string).hexsha + except (ODBError, GitCommandError, ValueError): pass return PushInfo(flags, from_ref, to_ref_string, remote, old_commit, summary, local_hash) diff --git a/test/test_remote.py b/test/test_remote.py index e1c6c9c83..3c390d445 100644 --- a/test/test_remote.py +++ b/test/test_remote.py @@ -581,6 +581,38 @@ def test_push_revision_sources(self, rw_repo): self.assertIsNone(info.local_ref) self.assertEqual(info.local_hash, parent.hexsha) + # A ref spelled like the abbreviated ID git prints must not win over the object. + rw_repo.create_head(rw_repo.git.rev_parse("--short", parent.hexsha), rw_repo.head.commit) + remote.push("HEAD:refs/heads/pushed_ref") + remote.fetch() + (info,) = remote.push("self/pushed_ref~1:refs/heads/pushed_ref", force=True) + self.assertEqual(info.local_hash, parent.hexsha) + + # A fully qualified revision is not a reference either. + source = rw_repo.create_head("push_source", rw_repo.head.commit) + (info,) = remote.push("%s~1:refs/heads/pushed_full" % source.path) + self.assertIsNone(info.local_ref) + self.assertEqual(info.local_hash, parent.hexsha) + + # A failed lookup keeps the result without a hash. + with mock.patch.object(rw_repo, "rev_parse", side_effect=GitCommandError("rev-parse", 128)): + (info,) = remote.push("HEAD~1:refs/heads/pushed_lookup") + self.assertTrue(info.flags & PushInfo.NEW_HEAD) + self.assertIsNone(info.local_hash) + + run = Git._call_process_safe + + def fail_disambiguate(git, method, *args, **kwargs): + if method == "rev_parse" and args and str(args[0]).startswith("--disambiguate="): + raise GitCommandError("rev-parse", 128) + return run(git, method, *args, **kwargs) + + remote.push("HEAD:refs/heads/pushed_ref") + with mock.patch.object(Git, "_call_process_safe", fail_disambiguate): + (info,) = remote.push("HEAD~1:refs/heads/pushed_ref", force=True) + self.assertTrue(info.flags & PushInfo.FORCED_UPDATE) + self.assertIsNone(info.local_hash) + @with_rw_repo("HEAD", bare=True) def test_creation_and_removal(self, bare_rw_repo): new_name = "test_new_one" From 056d90aaeda2fef4bed22d74076de7a4b6aaf56b Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:02:58 +0100 Subject: [PATCH 3/9] fix(remote): split push status refspecs at the final colon Git prints the complete source expression in porcelain output. A tree-path expression such as `HEAD:file.txt` includes a colon of its own. Splitting on every colon made GitPython discard the status even though Git had created the destination tag. Split only at the final colon so revision lookup receives the full source expression. Test the result and the tag's object ID on the CLI and Gix backends. Agent-Model: unknown --- git/remote.py | 2 +- test/test_remote.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/git/remote.py b/git/remote.py index 0eba7d093..abf9ff37f 100644 --- a/git/remote.py +++ b/git/remote.py @@ -236,7 +236,7 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo": # END handle control character # from_to handling - from_ref_string, to_ref_string = from_to.split(":") + from_ref_string, to_ref_string = from_to.rsplit(":", 1) from_ref: Union[SymbolicReference, None] = None is_revision = False if not flags & cls.DELETED and from_ref_string != "(delete)": diff --git a/test/test_remote.py b/test/test_remote.py index 3c390d445..4130a7606 100644 --- a/test/test_remote.py +++ b/test/test_remote.py @@ -554,6 +554,17 @@ def test_fetch_prune_skips_deleted_refs(self, rw_repo): "pruned refs are skipped without a warning", ) + @with_rw_repo("HEAD", bare=False) + def test_push_tree_path_source(self, rw_repo): + remote = rw_repo.create_remote("self", rw_repo.git_dir) + blob = next(rw_repo.head.commit.tree.traverse(predicate=lambda item, depth: item.type == "blob")) + + (info,) = remote.push(f"HEAD:{blob.path}:refs/tags/snapshot") + + self.assertIsNone(info.local_ref) + self.assertEqual(info.local_hash, blob.hexsha) + self.assertEqual(rw_repo.tags.snapshot.object.hexsha, blob.hexsha) + @with_rw_repo("HEAD", bare=False) def test_push_revision_sources(self, rw_repo): remote = rw_repo.create_remote("self", rw_repo.git_dir) From 445287e475b56c67edd2af370a099162ce827e67 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:03:20 +0100 Subject: [PATCH 4/9] fix(remote): retain push status when revision validation rejects a source Git accepts an option-shaped revision such as `-release~1` in a push refspec after `--`. The separate revision query rejects it, and the uncaught `UnsafeOptionError` previously stopped the stdout reader and lost later statuses. Treat the validation failure as an unavailable hash and retain the status. A mixed push regression checks that both results survive and that the receiver got the snapshot on both backends. Agent-Model: unknown --- git/remote.py | 4 ++-- test/test_remote.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/git/remote.py b/git/remote.py index abf9ff37f..edfa3d1ac 100644 --- a/git/remote.py +++ b/git/remote.py @@ -32,7 +32,7 @@ from git.cmd import Git, handle_process_output from git.compat import force_text from git.config import GitConfigParser, SectionConstraint, cp -from git.exc import GitCommandError, ODBError +from git.exc import GitCommandError, ODBError, UnsafeOptionError from git.refs import Reference, RemoteReference, SymbolicReference, TagReference from git.types import AnyGitObject, Literal, PathLike from git.util import ( @@ -289,7 +289,7 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo": local_hash = oids[0] if len(oids) == 1 else None else: local_hash = remote.repo.rev_parse(from_ref_string).hexsha - except (ODBError, GitCommandError, ValueError): + except (ODBError, GitCommandError, UnsafeOptionError, ValueError): pass return PushInfo(flags, from_ref, to_ref_string, remote, old_commit, summary, local_hash) diff --git a/test/test_remote.py b/test/test_remote.py index 4130a7606..e9da72722 100644 --- a/test/test_remote.py +++ b/test/test_remote.py @@ -565,6 +565,21 @@ def test_push_tree_path_source(self, rw_repo): self.assertEqual(info.local_hash, blob.hexsha) self.assertEqual(rw_repo.tags.snapshot.object.hexsha, blob.hexsha) + @with_rw_repo("HEAD", bare=False) + def test_push_option_like_revision_source(self, rw_repo): + remote = rw_repo.create_remote("self", rw_repo.git_dir) + rw_repo.git.update_ref("refs/tags/-release", "HEAD") + + result = remote.push(["-release~1:refs/heads/snapshot", "HEAD:refs/heads/ordinary"]) + + infos = {info.remote_ref_string: info for info in result} + self.assertEqual(set(infos), {"refs/heads/snapshot", "refs/heads/ordinary"}) + self.assertTrue(infos["refs/heads/snapshot"].flags & PushInfo.NEW_HEAD) + self.assertIsNone(infos["refs/heads/snapshot"].local_ref) + self.assertIsNone(infos["refs/heads/snapshot"].local_hash) + self.assertEqual(infos["refs/heads/ordinary"].local_ref, rw_repo.head) + self.assertEqual(rw_repo.heads.snapshot.commit, rw_repo.head.commit.parents[0]) + @with_rw_repo("HEAD", bare=False) def test_push_revision_sources(self, rw_repo): remote = rw_repo.create_remote("self", rw_repo.git_dir) From e021277bf12ac94968388a2bed56e53173fb553e Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:03:36 +0100 Subject: [PATCH 5/9] fix(remote): drain push status output before resolving hashes Resolving revision sources in the stdout reader made optional object lookups count against `kill_after_timeout`. A push could finish on the receiver while the reader was still resolving hashes, report a timeout, and lose statuses later in the stream. Collect the raw porcelain lines during the timed drain and parse the captured lines once the drain returns. A subprocess regression checks that disambiguation happens after stdout closes and that both statuses are retained. The partial-timeout test still passes on both backends. Agent-Model: unknown --- git/remote.py | 17 +++++++++-------- test/test_remote.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/git/remote.py b/git/remote.py index edfa3d1ac..411d03327 100644 --- a/git/remote.py +++ b/git/remote.py @@ -913,22 +913,23 @@ def _get_push_info( # to override the previous one. This is why we read the bytes manually. progress_handler = progress.new_message_handler() output: PushInfoList = PushInfoList() - - def stdout_handler(line: str) -> None: - try: - output.append(PushInfo._from_line(self, line)) - except ValueError: - # If an error happens, additional info is given which we parse below. - pass + push_info_lines: List[str] = [] handle_process_output( proc, - stdout_handler, + push_info_lines.append, progress_handler, finalizer=None, decode_streams=False, kill_after_timeout=kill_after_timeout, ) + # Optional lookups are independent of the push's process timeout. + for line in list(push_info_lines): + try: + output.append(PushInfo._from_line(self, line)) + except ValueError: + # Non-status lines are handled through stderr and the exit code below. + pass stderr_text = "\n".join(progress.error_lines) try: proc.wait(stderr=stderr_text) diff --git a/test/test_remote.py b/test/test_remote.py index e9da72722..0d3fd6cf4 100644 --- a/test/test_remote.py +++ b/test/test_remote.py @@ -1196,6 +1196,34 @@ def stall(): class TestTimeouts(TestBase): + @skipIf(sys.platform == "win32", "requires POSIX timeout signalling") + @with_rw_repo("HEAD", bare=False) + def test_push_hash_lookup_waits_for_status_output(self, repo): + current = repo.head.commit + parent = current.parents[0] + lines = ( + f"+\tHEAD~1:refs/heads/snapshot\t{current.hexsha[:12]}...{parent.hexsha[:12]} (forced update)\n" + "=\tHEAD:refs/heads/ordinary\t[up to date]" + ) + process = repo.git.execute( + [sys.executable, "-c", f"print({lines!r})"], as_process=True, universal_newlines=True + ) + run = Git._call_process_safe + stream_closed = [] + + def track_disambiguate(git, method, *args, **kwargs): + if method == "rev_parse" and args[0].startswith("--disambiguate="): + stream_closed.append(process.stdout.closed) + return run(git, method, *args, **kwargs) + + with mock.patch.object(Git, "_call_process_safe", track_disambiguate): + result = repo.remote("origin")._get_push_info(process, None, kill_after_timeout=5) + + result.raise_if_error() + assert stream_closed == [True] + assert [info.remote_ref_string for info in result] == ["refs/heads/snapshot", "refs/heads/ordinary"] + assert result[0].local_hash == parent.hexsha + @skipIf(sys.platform == "win32", "requires POSIX timeout signalling") @with_rw_repo("HEAD", bare=False) def test_timeout_partial_push(self, repo): From c8ed494ca267bdbeba536d7978bf47d884e90dde Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:03:54 +0100 Subject: [PATCH 6/9] fix(remote): require an exact reference for a push source A describe expression derived from a tag named `refs/releases/base` starts with `refs/`. `Reference.from_path()` accepts that prefix, so a successful push returned a reference that did not exist and discarded the pushed commit's ID. Use the shared exact-reference lookup before setting `local_ref`. A regression pushes the describe expression and verifies the destination and reported commit IDs on both backends. Agent-Model: unknown --- git/remote.py | 5 ++++- test/test_remote.py | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/git/remote.py b/git/remote.py index 411d03327..3bb015793 100644 --- a/git/remote.py +++ b/git/remote.py @@ -246,9 +246,12 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo": is_revision = True else: try: - from_ref = Reference.from_path(remote.repo, from_ref_string) + candidate = Reference.from_path(remote.repo, from_ref_string) + candidate._get_ref_info(remote.repo, from_ref_string) except ValueError: is_revision = True + else: + from_ref = candidate # Commit handling, could be message or commit info old_commit: Optional[str] = None diff --git a/test/test_remote.py b/test/test_remote.py index 0d3fd6cf4..f3e46947b 100644 --- a/test/test_remote.py +++ b/test/test_remote.py @@ -580,6 +580,20 @@ def test_push_option_like_revision_source(self, rw_repo): self.assertEqual(infos["refs/heads/ordinary"].local_ref, rw_repo.head) self.assertEqual(rw_repo.heads.snapshot.commit, rw_repo.head.commit.parents[0]) + @with_rw_repo("HEAD", bare=False) + def test_push_describe_source_with_ref_prefix(self, rw_repo): + remote = rw_repo.create_remote("self", rw_repo.git_dir) + current = rw_repo.head.commit + rw_repo.create_tag("refs/releases/base", current.parents[0]) + source = rw_repo.git.describe("--tags", "--long", "--match=refs/releases/base") + self.assertTrue(source.startswith("refs/releases/base-")) + + (info,) = remote.push(f"{source}:refs/heads/snapshot") + + self.assertIsNone(info.local_ref) + self.assertEqual(info.local_hash, current.hexsha) + self.assertEqual(rw_repo.heads.snapshot.commit, current) + @with_rw_repo("HEAD", bare=False) def test_push_revision_sources(self, rw_repo): remote = rw_repo.create_remote("self", rw_repo.git_dir) From b06a835a2f5553c8f0bd111077f9ec56b863cac8 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:06:11 +0100 Subject: [PATCH 7/9] fix(remote): capture revision sources before the push changes refs A push can update the tracking ref that another refspec uses as a revision base. Looking up the source after the push can return a different commit. The old lookup also omitted per-call Git settings such as `GIT_NO_REPLACE_OBJECTS`. Resolve explicit sources with the push environment before starting Git. Prefer object IDs reported in update summaries. Leave the hash unset if Git did not report it and the source could not be captured. Skip capture when one-shot Git options are reserved for the push. Regressions verify a combined tracking-ref update and snapshot, per-call replacement settings, and one-shot options. The focused push tests pass on the CLI and Gix backends. Agent-Model: unknown --- doc/gix-backend.md | 1 + doc/source/changes.rst | 3 +- git/remote.py | 104 +++++++++++++++++++++++++++++------------ test/test_remote.py | 47 +++++++++++++++++-- 4 files changed, 121 insertions(+), 34 deletions(-) diff --git a/doc/gix-backend.md b/doc/gix-backend.md index f2ad15dcb..749e6a3f1 100644 --- a/doc/gix-backend.md +++ b/doc/gix-backend.md @@ -385,6 +385,7 @@ and predate the current fallback; they do not establish native coverage. | Standalone discovery helpers | Native storage directories and gitfiles reopened at their canonical native Git directory | Rejected candidates and the same layout/environment guards as `Repo` opening; GIX-14 | | `Repo.rev_parse`, `rev_parse` metadata queries | Revision lookup, common directory, object format, bare flag, worktree root, fixed `modules`/`COMMIT_EDITMSG` locations | Repository-format validation, other metadata paths, symlinked metadata leaves, message searches and describe forms; GIX-1/14/17/22 | | Revision path/mode metadata | Native revision specification, including tree paths and index stages | Custom/sparse indexes, unsupported revision grammar or path normalization | +| `Remote.push` status | Managed revision lookup for explicit sources and exact reference lookup in the repository's default context | Git handles transport, abbreviated summary IDs, and exact reference checks with per-call environment overrides | | Tree enumeration, `ls_tree` | Native tree entries with modes, names, and object IDs | Other command options; entries with modes Git canonicalizes or that do not round-trip through native tree encoding; GIX-36 | | Reference object reads | One exact native lookup for direct, symbolic and absent references | Partial names and native decoding errors | | Reference-name validation | Native full-name validation without opening a repository | Standalone names outside the native grammar; GIX-20 | diff --git a/doc/source/changes.rst b/doc/source/changes.rst index c58020c99..6061e5d89 100644 --- a/doc/source/changes.rst +++ b/doc/source/changes.rst @@ -117,7 +117,8 @@ API changes upstream location; remote tracking branches retain their existing behavior. * ``Remote.push()`` no longer drops results whose source is not a reference, such as a commit hash or ``HEAD~1``. Their ``PushInfo.local_ref`` is ``None``, - and the new ``PushInfo.local_hash`` holds the hash of the pushed object. + and the new ``PushInfo.local_hash`` holds the hash reported by Git or + resolved from an explicit source before the push, when available. * ``GitCmdObjectDB`` no longer inherits ``LooseObjectDB``. Its object reads, writes, existence checks, and enumeration use Git, including packed objects. Precompressed input streams and custom object-output writers are unsupported. diff --git a/git/remote.py b/git/remote.py index 3bb015793..65c715fba 100644 --- a/git/remote.py +++ b/git/remote.py @@ -19,10 +19,12 @@ Dict, Iterator, List, + Mapping, NoReturn, Optional, Sequence, Set, + Tuple, TypeVar, Union, cast, @@ -32,7 +34,7 @@ from git.cmd import Git, handle_process_output from git.compat import force_text from git.config import GitConfigParser, SectionConstraint, cp -from git.exc import GitCommandError, ODBError, UnsafeOptionError +from git.exc import GitCommandError, UnsafeOptionError from git.refs import Reference, RemoteReference, SymbolicReference, TagReference from git.types import AnyGitObject, Literal, PathLike from git.util import ( @@ -49,6 +51,7 @@ from git.repo.base import Repo _T_RemoteName = TypeVar("_T_RemoteName", bound=Union[str, "Remote"]) +_PushSource = Tuple[Optional[SymbolicReference], Optional[str]] flagKeyLiteral = Literal[" ", "!", "+", "-", "*", "=", "t", "?"] @@ -125,8 +128,8 @@ class PushInfo(IterableObj): # It is None if the ref was deleted, or if the pushed source # was not a reference, like a commit hash or HEAD~1. info.local_hash # Hash of the pushed object if the source was not a - # reference, otherwise None. For new and rejected refs git - # prints no hash, so the source is resolved after the push. + # reference and the hash was reported by Git or could be + # resolved before the push. Otherwise None. info.remote_ref_string # path to the remote reference located on the remote side info.remote_ref # Remote Reference on the local side corresponding to # the remote_ref_string. It can be a TagReference as well. @@ -222,7 +225,30 @@ def remote_ref(self) -> Union[RemoteReference, TagReference]: # END @classmethod - def _from_line(cls, remote: "Remote", line: str) -> "PushInfo": + def _source_ref( + cls, remote: "Remote", source: str, env: Optional[Mapping[str, str]] + ) -> Optional[SymbolicReference]: + # Git also prints revision expressions here, including ones under refs/. + if cls._re_revision_syntax.search(source): + return None + try: + ref = Reference.from_path(remote.repo, source) + if env: + remote.repo.git._call_process_safe("show_ref", "--exists", "--", source, env=env) + else: + ref._get_ref_info(remote.repo, source) + except (GitCommandError, ValueError): + return None + return ref + + @classmethod + def _from_line( + cls, + remote: "Remote", + line: str, + sources: Optional[Mapping[str, _PushSource]] = None, + env: Optional[Mapping[str, str]] = None, + ) -> "PushInfo": """Create a new :class:`PushInfo` instance as parsed from line which is expected to be like refs/heads/master:refs/heads/master 05d2687..1d0568e as bytes.""" control_character, from_to, summary = line.split("\t", 3) @@ -238,20 +264,12 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo": # from_to handling from_ref_string, to_ref_string = from_to.rsplit(":", 1) from_ref: Union[SymbolicReference, None] = None - is_revision = False + local_hash: Optional[str] = None if not flags & cls.DELETED and from_ref_string != "(delete)": - # Git prints the source as it was given, which can be any revision. - # from_path() would accept one under refs/, like refs/heads/main~1. - if cls._re_revision_syntax.search(from_ref_string): - is_revision = True + if sources is not None and from_ref_string in sources: + from_ref, local_hash = sources[from_ref_string] else: - try: - candidate = Reference.from_path(remote.repo, from_ref_string) - candidate._get_ref_info(remote.repo, from_ref_string) - except ValueError: - is_revision = True - else: - from_ref = candidate + from_ref = cls._source_ref(remote, from_ref_string, env) # Commit handling, could be message or commit info old_commit: Optional[str] = None @@ -281,19 +299,20 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo": old_commit = old_sha # END message handling - local_hash: Optional[str] = None - if is_revision: - # The push may have moved a ref the revision is relative to, like - # origin/main~1, so prefer the hash git reports as pushed. - try: - if new_sha: + if from_ref is None and new_sha: + # Prefer the object ID reported by the push over the pre-push lookup. + local_hash = None + if remote.repo.re_hexsha_only.fullmatch(new_sha): + local_hash = new_sha + elif env is not None: + try: # rev-parse would prefer a ref spelled like the abbreviated ID. - oids = remote.repo.git._call_process_safe("rev_parse", "--disambiguate=%s" % new_sha).split() + oids = remote.repo.git._call_process_safe( + "rev_parse", "--disambiguate=%s" % new_sha, env=env + ).split() local_hash = oids[0] if len(oids) == 1 else None - else: - local_hash = remote.repo.rev_parse(from_ref_string).hexsha - except (ODBError, GitCommandError, UnsafeOptionError, ValueError): - pass + except (GitCommandError, UnsafeOptionError, ValueError): + pass return PushInfo(flags, from_ref, to_ref_string, remote, old_commit, summary, local_hash) @@ -907,6 +926,9 @@ def _get_push_info( proc: "Git.AutoInterrupt", progress: Union[Callable[..., Any], RemoteProgress, None], kill_after_timeout: Union[None, float] = None, + *, + sources: Optional[Mapping[str, _PushSource]] = None, + env: Optional[Mapping[str, str]] = None, ) -> PushInfoList: progress = to_progress_instance(progress) @@ -929,7 +951,7 @@ def _get_push_info( # Optional lookups are independent of the push's process timeout. for line in list(push_info_lines): try: - output.append(PushInfo._from_line(self, line)) + output.append(PushInfo._from_line(self, line, sources, env)) except ValueError: # Non-status lines are handled through stderr and the exit code below. pass @@ -948,6 +970,27 @@ def _get_push_info( return output + def _push_sources(self, refspecs: Sequence[str], env: Mapping[str, str]) -> Dict[str, _PushSource]: + sources: Dict[str, _PushSource] = {} + for refspec in refspecs: + source, separator, _ = refspec.lstrip("+").rpartition(":") + if not separator or not source or source in sources: + continue + ref = PushInfo._source_ref(self, source, env) + oid = None + if ref is None: + try: + Git._check_operand(source, "revision") + resolved = self.repo.git._call_process_safe( + "rev_parse", "--verify", "--quiet", "--end-of-options", source, env=env + ) + if self.repo.re_hexsha_only.fullmatch(resolved): + oid = resolved + except (GitCommandError, UnsafeOptionError, ValueError): + pass + sources[source] = ref, oid + return sources + def _assert_refspec(self) -> None: """Turns out we can't deal with remotes if the refspec is missing.""" config = self.config_reader @@ -1199,6 +1242,9 @@ def push( unsafe_options=self.unsafe_git_push_options, ) + # Do not consume Git options reserved for the next command. + env = None if self.repo.git._git_options else kwargs.get("env") or {} + sources = self._push_sources(refspec, env) if env is not None else None proc = self.repo.git._call_process_safe( "push", "--", @@ -1211,7 +1257,7 @@ def push( kill_after_timeout=kill_after_timeout, **kwargs, ) - return self._get_push_info(proc, progress, kill_after_timeout=kill_after_timeout) + return self._get_push_info(proc, progress, kill_after_timeout=kill_after_timeout, sources=sources, env=env) @property def config_reader(self) -> SectionConstraint[GitConfigParser]: diff --git a/test/test_remote.py b/test/test_remote.py index f3e46947b..16139a3a5 100644 --- a/test/test_remote.py +++ b/test/test_remote.py @@ -594,6 +594,40 @@ def test_push_describe_source_with_ref_prefix(self, rw_repo): self.assertEqual(info.local_hash, current.hexsha) self.assertEqual(rw_repo.heads.snapshot.commit, current) + @with_rw_repo("HEAD", bare=False) + def test_push_snapshots_source_before_updating_tracking_ref(self, rw_repo): + remote = rw_repo.create_remote("self", rw_repo.git_dir) + current = rw_repo.head.commit + parent = current.parents[0] + previous_source = parent.parents[0] + remote.push(f"{parent.hexsha}:refs/heads/pushed_ref").raise_if_error() + + result = remote.push(["HEAD:refs/heads/pushed_ref", "self/pushed_ref~1:refs/heads/snapshot"]) + + result.raise_if_error() + infos = {info.remote_ref_string: info for info in result} + self.assertEqual(infos["refs/heads/snapshot"].local_hash, previous_source.hexsha) + self.assertEqual(rw_repo.heads.snapshot.commit, previous_source) + self.assertEqual(rw_repo.commit("refs/remotes/self/pushed_ref"), current) + + @with_rw_repo("HEAD", bare=False) + def test_push_resolves_revision_source_with_call_environment(self, rw_repo): + remote = rw_repo.create_remote("self", rw_repo.git_dir) + parent = rw_repo.head.commit.parents[0] + rw_repo.git.replace("HEAD", parent.hexsha) + self.assertEqual(rw_repo.git.rev_parse("HEAD~1"), parent.parents[0].hexsha) + + (info,) = remote.push("HEAD~1:refs/heads/snapshot", env={"GIT_NO_REPLACE_OBJECTS": "1"}) + + self.assertIsNone(info.local_ref) + self.assertEqual(info.local_hash, parent.hexsha) + self.assertEqual(rw_repo.heads.snapshot.commit, parent) + + rw_repo.git(no_replace_objects=True) + (info,) = remote.push("HEAD~1:refs/heads/snapshot_once") + self.assertIsNone(info.local_hash) + self.assertEqual(rw_repo.heads.snapshot_once.commit, parent) + @with_rw_repo("HEAD", bare=False) def test_push_revision_sources(self, rw_repo): remote = rw_repo.create_remote("self", rw_repo.git_dir) @@ -634,14 +668,19 @@ def test_push_revision_sources(self, rw_repo): self.assertIsNone(info.local_ref) self.assertEqual(info.local_hash, parent.hexsha) + run = Git._call_process_safe + + def fail_revision(git, method, *args, **kwargs): + if method == "rev_parse" and args == ("--verify", "--quiet", "--end-of-options", "HEAD~1"): + raise GitCommandError("rev-parse", 128) + return run(git, method, *args, **kwargs) + # A failed lookup keeps the result without a hash. - with mock.patch.object(rw_repo, "rev_parse", side_effect=GitCommandError("rev-parse", 128)): + with mock.patch.object(Git, "_call_process_safe", fail_revision): (info,) = remote.push("HEAD~1:refs/heads/pushed_lookup") self.assertTrue(info.flags & PushInfo.NEW_HEAD) self.assertIsNone(info.local_hash) - run = Git._call_process_safe - def fail_disambiguate(git, method, *args, **kwargs): if method == "rev_parse" and args and str(args[0]).startswith("--disambiguate="): raise GitCommandError("rev-parse", 128) @@ -1231,7 +1270,7 @@ def track_disambiguate(git, method, *args, **kwargs): return run(git, method, *args, **kwargs) with mock.patch.object(Git, "_call_process_safe", track_disambiguate): - result = repo.remote("origin")._get_push_info(process, None, kill_after_timeout=5) + result = repo.remote("origin")._get_push_info(process, None, kill_after_timeout=5, env={}) result.raise_if_error() assert stream_closed == [True] From b46584279d0716e8c76f82102031f16bfe62c7b5 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:07:22 +0100 Subject: [PATCH 8/9] fix(gix): resolve push remote selectors with Git With `push.default=upstream` and a mirror selected by `branch.main.pushRemote`, Git resolves `@{push}` through `mirror/main`. GixPython 0.4.0 resolves it through `origin/main`, so the Gix backend reported an object ID different from the one the push sent. Route push selectors through the managed Git fallback and record the open mismatch as GIX-45. The integration test verifies the receiver's object ID and the fallback on SHA-1 and SHA-256. The remote, revision, and CLI safety tests pass on both backends. Agent-Model: unknown --- doc/gix-backend.md | 3 ++- git/_backend.py | 4 +++- test/test_remote_cli.py | 20 +++++++++++++++++++- tests/fixtures/remote-cli.sh | 11 +++++++++++ 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/doc/gix-backend.md b/doc/gix-backend.md index 749e6a3f1..c9d64870f 100644 --- a/doc/gix-backend.md +++ b/doc/gix-backend.md @@ -383,7 +383,7 @@ and predate the current fallback; they do not establish native coverage. | Commit/tree serialization readback | Existing ODB stream; no separate `cat-file` process | The same storage and large-object fallbacks as ODB reads | | `Repo` opening/discovery | Native storage, worktree, object format and empty-tree metadata | Repository-format validation, unsupported layouts/environment and native validation gaps; GIX-1/14/19 | | Standalone discovery helpers | Native storage directories and gitfiles reopened at their canonical native Git directory | Rejected candidates and the same layout/environment guards as `Repo` opening; GIX-14 | -| `Repo.rev_parse`, `rev_parse` metadata queries | Revision lookup, common directory, object format, bare flag, worktree root, fixed `modules`/`COMMIT_EDITMSG` locations | Repository-format validation, other metadata paths, symlinked metadata leaves, message searches and describe forms; GIX-1/14/17/22 | +| `Repo.rev_parse`, `rev_parse` metadata queries | Revision lookup, common directory, object format, bare flag, worktree root, fixed `modules`/`COMMIT_EDITMSG` locations | Repository-format validation, other metadata paths, symlinked metadata leaves, message searches, describe forms and push selectors; GIX-1/14/17/22/46 | | Revision path/mode metadata | Native revision specification, including tree paths and index stages | Custom/sparse indexes, unsupported revision grammar or path normalization | | `Remote.push` status | Managed revision lookup for explicit sources and exact reference lookup in the repository's default context | Git handles transport, abbreviated summary IDs, and exact reference checks with per-call environment overrides | | Tree enumeration, `ls_tree` | Native tree entries with modes, names, and object IDs | Other command options; entries with modes Git canonicalizes or that do not round-trip through native tree encoding; GIX-36 | @@ -1020,6 +1020,7 @@ identify the historical fixture where needed. | 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-44 | Bug (open) | With Git 2.54.0 and GixPython 0.3.0, the `branch-dot-alias` case of `submodule-cases.sh` sets `HEAD` to `refs/heads/dev`, which points to `refs/heads/master`. `Repository.head_name()` and `Repository.head_ref().name()` return `refs/heads/dev`. `git symbolic-ref HEAD` returns `refs/heads/master`, and `git submodule update --remote` selects `origin/master` for `branch = .`. `test_update_to_latest_revision_follows_superproject_branch_alias` verifies branch selection on clone and later updates. Redirect `dev` to `refs/heads/missing` and Git returns that terminal name, while `Reference.follow_to_object()` raises a missing-ref error. | Expose the terminal symbolic target with Git-compatible handling of unborn, detached and invalid references. `Submodule._branch_for_update()` uses recursive `git symbolic-ref --quiet -- HEAD` through the CLI fallback. | | GIX-45 | Bug (open) | Git 2.54.0 `submodule update --remote --no-fetch` rejects a bare `branch` key in `.gitmodules` with `missing value for 'submodule.module.branch'`, including before or after `branch = dev`. In GixPython 0.3.0 and 0.4.0, `ModulesFile.from_bytes()` accepts the bare key and `ModulesFile.branch()` returns `None` for an absent or single bare key. `ConfigFile.boolean()` distinguishes these two inputs with `None` and `True`, respectively. When the bare key precedes `branch = dev`, both `ModulesFile.branch().name_bytes()` and `ConfigFile.string()` return `b"dev"`. For an explicit `branch =` with an `origin` remote, Git attempts to resolve `refs/remotes/origin/`, `ModulesFile.branch().name_bytes()` returns `b"HEAD"`, and `ConfigFile.string()` returns `b""`. | Reject valueless branches in a Git-compatible mode or expose all raw values, including implicit ones. `submodule_config()` falls back to the Git config reader for possible bare `branch` keys and uses `ConfigFile.string()` for assigned values. `test_valueless_branch_is_invalid` covers listing and rereads with a single bare key and one followed by an assignment. | +| GIX-46 | Bug (open) | On macOS with Git 2.54.0 and GixPython 0.4.0, `remote-cli.sh push-mirror` sets `main` to track `origin/main` with `branch.main.pushRemote=mirror`, `remote.mirror.mirror=true` and `push.default=upstream`. `git rev-parse --verify '@{push}'` resolves `mirror/main`, and `git push origin '@{push}:refs/heads/snapshot'` sends that commit. `Repository.rev_parse_single(b"@{push}")` returns `origin/main`. Both SHA-1 and SHA-256 reproduce the mismatch, including case-insensitive `@{PuSh}`. | Match Git's push remote and tracking-ref selection for mirror remotes. `_check_revision_grammar()` uses Git to resolve push selectors, including when `Remote.push()` captures a `PushInfo.local_hash`. `test_push_uses_mirror_remote_selector` checks the reported ID against the receiver and verifies CLI fallback on both object formats. | 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 6f1878ca1..b010e3611 100644 --- a/git/_backend.py +++ b/git/_backend.py @@ -171,10 +171,12 @@ def _check_revision_grammar(ref: str) -> None: prefix, opener, remainder = ref.partition("@{") if opener and ":" not in prefix: selector, closer, _ = remainder.partition("}") + if closer and selector.lower() == "push": + raise _Unsupported("push remote selectors (GIX-46)") 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"} + or selector.lower() in {"u", "upstream", "p"} ): raise _Unsupported("textual reflog dates (GIX-39)") diff --git a/test/test_remote_cli.py b/test/test_remote_cli.py index 1e5ea4b41..3cbf33e3c 100644 --- a/test/test_remote_cli.py +++ b/test/test_remote_cli.py @@ -6,7 +6,7 @@ import pytest -from git import FetchInfo, Repo +from git import FetchInfo, Repo, _backend from git.objects.submodule.util import sm_section from test.lib.fixtures import writable_fixture @@ -17,6 +17,24 @@ def remote_fixture(request): yield temporary.path().resolve() +@pytest.mark.parametrize("remote_fixture", [("push-mirror", obj) for obj in ("sha1", "sha256")], indirect=True) +def test_push_uses_mirror_remote_selector(remote_fixture): + with Repo(remote_fixture / "source") as source, Repo(remote_fixture / "clone") as clone: + expected = clone.commit("refs/remotes/mirror/main") + assert expected != clone.commit("refs/remotes/origin/main") + assert clone.git.rev_parse("--verify", "@{push}") == expected.hexsha + fallback = ("rev_parse", "CLI: push remote selectors (GIX-46)") + before = _backend.statistics().get(fallback, 0) + + (info,) = clone.remote("origin").push("@{push}:refs/heads/snapshot") + + assert source.heads.snapshot.commit == expected + assert info.local_ref is None + assert info.local_hash == expected.hexsha + if _backend.name == "gix": + assert _backend.statistics().get(fallback, 0) == before + 1 + + @pytest.mark.parametrize( "remote_fixture", [("fetch", obj, refs) for obj in ("sha1", "sha256") for refs in ("files", "reftable")], diff --git a/tests/fixtures/remote-cli.sh b/tests/fixtures/remote-cli.sh index 9f0cf4f2e..a47dfef7f 100644 --- a/tests/fixtures/remote-cli.sh +++ b/tests/fixtures/remote-cli.sh @@ -4,6 +4,17 @@ set -eu git init --initial-branch=main --object-format="${2:-sha1}" --ref-format="${3:-files}" source git -C source commit --allow-empty -m first case "$1" in + push-mirror) + git clone --bare source mirror + git -C source commit --allow-empty -m second + git clone source clone + git -C clone remote set-url origin ../source + git -C clone remote add mirror ../mirror + git -C clone fetch mirror + git -C clone config branch.main.pushRemote mirror + git -C clone config remote.mirror.mirror true + git -C clone config push.default upstream + ;; fetch) git clone source clone git -C clone remote set-url origin ../source From 2d6d27a0e8628dbf73964a86fc7d0d5914aa02cf Mon Sep 17 00:00:00 2001 From: Byron Date: Thu, 26 Nov 2026 07:55:07 +0100 Subject: [PATCH 9/9] fix(git)!: scope one-shot options to the returned wrapper Rubber-stamp tests. Just a rubber-stamp for everything, but looked at the code at least to see if something sticks out. And what stuck out is statefulness of Git command execution. Calling `repo.git(**options)` used to queue options on the shared `Git` wrapper. A source lookup in `Remote.push()` could consume options meant for the push, so the push skipped that lookup and could leave `PushInfo.local_hash` unset. Return a separate wrapper that applies the options to its next subcommand. Chained calls still work, but discarding the wrapper no longer affects later repository operations. Remove the push guard and the commit hook's save-and-restore logic. For repository operations, use per-call environment overrides or `set_persistent_git_options()`. The non-network command, remote, index, and downstream compatibility tests passed on both CLI and Gix (307 passed per backend). Agent-Model: gpt-6.2-sol --- doc/source/changes.rst | 5 +++++ git/cmd.py | 28 ++++++++++++++++++++++------ git/index/fun.py | 5 ++--- git/remote.py | 7 +++---- test/test_git.py | 29 +++++++++++++++++++++++++++++ test/test_index.py | 20 ++++++-------------- test/test_remote.py | 7 ++++--- 7 files changed, 71 insertions(+), 30 deletions(-) diff --git a/doc/source/changes.rst b/doc/source/changes.rst index 6061e5d89..cca7195da 100644 --- a/doc/source/changes.rst +++ b/doc/source/changes.rst @@ -115,6 +115,11 @@ API changes current repository (``branch..remote=.``) as the upstream, instead of constructing an invalid ``refs/remotes/./...`` reference. Git resolves the upstream location; remote tracking branches retain their existing behavior. +* ``repo.git(**options)`` returns a separate ``Git`` wrapper whose next subcommand + receives the options. Chained calls such as ``repo.git(c="core.abbrev=12").log()`` + still work. A standalone ``repo.git(**options)`` call no longer affects later + repository operations; use per-call environment overrides or + ``set_persistent_git_options()`` instead. * ``Remote.push()`` no longer drops results whose source is not a reference, such as a commit hash or ``HEAD~1``. Their ``PushInfo.local_ref`` is ``None``, and the new ``PushInfo.local_hash`` holds the hash reported by Git or diff --git a/git/cmd.py b/git/cmd.py index 991a494a3..dd5dceeb2 100644 --- a/git/cmd.py +++ b/git/cmd.py @@ -19,8 +19,10 @@ import sys import threading import time +from copy import copy from subprocess import DEVNULL, PIPE, Popen from textwrap import dedent +from types import MemberDescriptorType # typing --------------------------------------------------------------------------- from typing import ( @@ -43,8 +45,8 @@ overload, ) -from git.compat import defenc, safe_decode, safe_encode from git import _backend +from git.compat import defenc, safe_decode, safe_encode from git.exc import ( CommandError, GitCommandError, @@ -340,7 +342,13 @@ def dashify(string: str) -> str: def slots_to_dict(self: "Git", exclude: Sequence[str] = ()) -> Dict[str, Any]: - return {s: getattr(self, s) for s in self.__slots__ if s not in exclude} + state = {} + for cls in reversed(type(self).__mro__): + for name, descriptor in vars(cls).items(): + if isinstance(descriptor, MemberDescriptorType) and name not in exclude: + with contextlib.suppress(AttributeError): + state[name] = descriptor.__get__(self) + return state def dict_to_slots_and__excluded_are_none(self: object, d: Mapping[str, Any], excluded: Sequence[str] = ()) -> None: @@ -648,7 +656,7 @@ class Git: ] def __getstate__(self) -> Dict[str, Any]: - return slots_to_dict(self, exclude=self._excluded_) + return {**getattr(self, "__dict__", {}), **slots_to_dict(self, exclude=self._excluded_)} def __setstate__(self, d: Dict[str, Any]) -> None: dict_to_slots_and__excluded_are_none(self, d, excluded=self._excluded_) @@ -1820,7 +1828,10 @@ def _unpack_args(cls, arg_list: Sequence[Any]) -> List[str]: return outlist def __call__(self, **kwargs: Any) -> "Git": - """Specify command line options to the git executable for a subcommand call. + """Return a separate Git wrapper with options for its next subcommand call. + + The original wrapper is unchanged. Discarding the returned wrapper discards + the one-shot options as well. :param kwargs: A dict of keyword arguments. @@ -1831,8 +1842,13 @@ def __call__(self, **kwargs: Any) -> "Git": git(work_tree='/tmp').difftool() """ - self._git_options = self.transform_kwargs(split_single_char_options=True, **kwargs) - return self + # The copy excludes cached cat-file processes, which must not be shared. + command = copy(self) + command._repo = self._repo + command._environment = self._environment.copy() + command._repository_environment = self._repository_environment.copy() + command._git_options = self.transform_kwargs(split_single_char_options=True, **kwargs) + return command @overload def _call_process( diff --git a/git/index/fun.py b/git/index/fun.py index 9a7868b52..8e3c381a2 100644 --- a/git/index/fun.py +++ b/git/index/fun.py @@ -8,6 +8,7 @@ from git.cmd import Git from git.exc import GitCommandError, HookExecutionError, UnsafeOptionError from git.types import PathLike + from .typ import BaseIndexEntry if TYPE_CHECKING: @@ -38,8 +39,7 @@ def run_commit_hook(name: str, index: "IndexFile", *args: str) -> None: raise UnsafeOptionError("Git arguments cannot contain NUL bytes") command = index.repo.git # Repo's automatic GIT_DIR bypasses Git's discovery-time ownership check. - one_shot_options, command._git_options = command._git_options, () - options = [*command._persistent_git_options, *one_shot_options] + options = list(command._persistent_git_options) discovery_env = {} if ( "GIT_DIR" in command._repository_environment @@ -57,7 +57,6 @@ def run_commit_hook(name: str, index: "IndexFile", *args: str) -> None: env=discovery_env, _repository_redirected="-C" in options, ) - command._git_options = one_shot_options try: index.repo.git._call_process_safe( "hook", diff --git a/git/remote.py b/git/remote.py index 65c715fba..9a87b558e 100644 --- a/git/remote.py +++ b/git/remote.py @@ -304,7 +304,7 @@ def _from_line( local_hash = None if remote.repo.re_hexsha_only.fullmatch(new_sha): local_hash = new_sha - elif env is not None: + else: try: # rev-parse would prefer a ref spelled like the abbreviated ID. oids = remote.repo.git._call_process_safe( @@ -1242,9 +1242,8 @@ def push( unsafe_options=self.unsafe_git_push_options, ) - # Do not consume Git options reserved for the next command. - env = None if self.repo.git._git_options else kwargs.get("env") or {} - sources = self._push_sources(refspec, env) if env is not None else None + env = kwargs.get("env") or {} + sources = self._push_sources(refspec, env) proc = self.repo.git._call_process_safe( "push", "--", diff --git a/test/test_git.py b/test/test_git.py index 5b1dd49de..f72f911c5 100644 --- a/test/test_git.py +++ b/test/test_git.py @@ -1008,6 +1008,35 @@ def test_single_char_git_options_are_passed_to_git(self): output_value = self.git(c="user.name=%s" % input_value).config("--get", "user.name") self.assertEqual(input_value, output_value) + def test_one_shot_options_belong_to_the_returned_wrapper(self): + with self.git.custom_environment(GIT_EDITOR="original"): + configured = self.git(c="core.editor=one-shot") + configured.update_environment(GIT_EDITOR="configured") + self.assertEqual(self.git.var("GIT_EDITOR"), "original") + self.assertEqual(configured.var("GIT_EDITOR"), "configured") + + configured = self.git(c="gitpython.oneShot=first") + other = self.git(c="gitpython.oneShot=second") + with self.assertRaises(GitCommandError): + self.git.config("--get", "gitpython.oneShot") + self.assertEqual(configured.config("--get", "gitpython.oneShot"), "first") + self.assertEqual(other.config("--get", "gitpython.oneShot"), "second") + with self.assertRaises(GitCommandError): + configured.config("--get", "gitpython.oneShot") + + def test_one_shot_options_preserve_subclass_state(self): + class CustomGit(Git): + __slots__ = ("label", "__dict__") + extra: str + + git = CustomGit(self.git.working_dir) + git.label = "label" + git.extra = "extra" + configured = git(version=True) + assert isinstance(configured, CustomGit) + self.assertEqual((configured.label, configured.extra), ("label", "extra")) + self.assertEqual(configured.NoOp(), git.version()) + def test_change_to_transform_kwargs_does_not_break_command_options(self): self.git.log(n=1) diff --git a/test/test_index.py b/test/test_index.py index 2b9487cbc..fca669863 100644 --- a/test/test_index.py +++ b/test/test_index.py @@ -19,8 +19,8 @@ import pytest from git import NULL_TREE, BlobFilter, Diff, Git, IndexFile, Object, Repo, Tree -from git.diff import NULL_TREE_SHA from git.compat import defenc +from git.diff import NULL_TREE_SHA from git.exc import ( CheckoutError, GitCommandError, @@ -35,8 +35,8 @@ from git.objects import Blob from git.util import Actor, cwd, hex_to_bin, rmtree from test.lib import PathLikeMock, TestBase, fixture, fixture_path, with_rw_directory, with_rw_repo -from test.lib.helper import symlinks_supported, xfail_if_raises from test.lib.fixtures import ROOT, fixture_repo, writable_fixture +from test.lib.helper import symlinks_supported, xfail_if_raises _logger = logging.getLogger(__name__) @@ -1286,7 +1286,7 @@ def test_pre_commit_hook_not_run_in_repository_git_refuses(self): output.unlink() def test_commit_hook_preserves_explicit_repository_selection(self): - for selection in ("one-shot", "persistent", "environment", "git-dir-option"): + for selection in ("persistent", "environment", "git-dir-option"): with self.subTest(selection=selection), fixture_repo("hook-ownership.sh", "regular", write=True) as repo: with Repo(repo.git_dir) as metadata: index = metadata.index @@ -1295,13 +1295,11 @@ def test_commit_hook_preserves_explicit_repository_selection(self): environment = {"GIT_DIR": ".git"} if selection == "environment" else {} with baseline.custom_environment(**environment), metadata.git.custom_environment(**environment): for command in (baseline, metadata.git): - if selection == "one-shot": - command(C=".git") - elif selection == "persistent": + if selection == "persistent": command.set_persistent_git_options(C=".git") elif selection == "git-dir-option": - command(git_dir=".git") - output = Path(repo.git_dir if selection in ("one-shot", "persistent") else repo.working_dir) + command.set_persistent_git_options(git_dir=".git") + output = Path(repo.git_dir if selection == "persistent" else repo.working_dir) output /= "output.txt" baseline.hook("run", "pre-commit") expected = output.read_text(encoding="utf-8") @@ -1309,12 +1307,6 @@ def test_commit_hook_preserves_explicit_repository_selection(self): run_commit_hook("pre-commit", index) self.assertEqual(output.read_text(encoding="utf-8"), expected) - metadata.git.set_persistent_git_options() - metadata.git(C="missing") - with self.assertRaises(GitCommandError): - run_commit_hook("pre-commit", index) - self.assertEqual(metadata.git.rev_parse("--git-dir"), str(metadata.git_dir)) - def test_pre_commit_hook_fail(self): with fixture_repo("index.sh", "hook-fail", write=True) as repo: with self.assertRaises(HookExecutionError) as caught: diff --git a/test/test_remote.py b/test/test_remote.py index 16139a3a5..8ecf40b6f 100644 --- a/test/test_remote.py +++ b/test/test_remote.py @@ -623,10 +623,11 @@ def test_push_resolves_revision_source_with_call_environment(self, rw_repo): self.assertEqual(info.local_hash, parent.hexsha) self.assertEqual(rw_repo.heads.snapshot.commit, parent) + # Discarding the configured wrapper must not affect the push. rw_repo.git(no_replace_objects=True) - (info,) = remote.push("HEAD~1:refs/heads/snapshot_once") - self.assertIsNone(info.local_hash) - self.assertEqual(rw_repo.heads.snapshot_once.commit, parent) + (info,) = remote.push("HEAD~1:refs/heads/snapshot_with_replace") + self.assertEqual(info.local_hash, parent.parents[0].hexsha) + self.assertEqual(rw_repo.heads.snapshot_with_replace.commit, parent.parents[0]) @with_rw_repo("HEAD", bare=False) def test_push_revision_sources(self, rw_repo):