Skip to content

Commit b06a835

Browse files
codexByron
authored andcommitted
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
1 parent c8ed494 commit b06a835

4 files changed

Lines changed: 121 additions & 34 deletions

File tree

‎doc/gix-backend.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,7 @@ and predate the current fallback; they do not establish native coverage.
385385
| 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 |
386386
| `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 |
387387
| Revision path/mode metadata | Native revision specification, including tree paths and index stages | Custom/sparse indexes, unsupported revision grammar or path normalization |
388+
| `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 |
388389
| 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 |
389390
| Reference object reads | One exact native lookup for direct, symbolic and absent references | Partial names and native decoding errors |
390391
| Reference-name validation | Native full-name validation without opening a repository | Standalone names outside the native grammar; GIX-20 |

‎doc/source/changes.rst‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,8 @@ API changes
117117
upstream location; remote tracking branches retain their existing behavior.
118118
* ``Remote.push()`` no longer drops results whose source is not a reference,
119119
such as a commit hash or ``HEAD~1``. Their ``PushInfo.local_ref`` is ``None``,
120-
and the new ``PushInfo.local_hash`` holds the hash of the pushed object.
120+
and the new ``PushInfo.local_hash`` holds the hash reported by Git or
121+
resolved from an explicit source before the push, when available.
121122
* ``GitCmdObjectDB`` no longer inherits ``LooseObjectDB``. Its object reads,
122123
writes, existence checks, and enumeration use Git, including packed objects.
123124
Precompressed input streams and custom object-output writers are unsupported.

‎git/remote.py‎

Lines changed: 75 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,12 @@
1919
Dict,
2020
Iterator,
2121
List,
22+
Mapping,
2223
NoReturn,
2324
Optional,
2425
Sequence,
2526
Set,
27+
Tuple,
2628
TypeVar,
2729
Union,
2830
cast,
@@ -32,7 +34,7 @@
3234
from git.cmd import Git, handle_process_output
3335
from git.compat import force_text
3436
from git.config import GitConfigParser, SectionConstraint, cp
35-
from git.exc import GitCommandError, ODBError, UnsafeOptionError
37+
from git.exc import GitCommandError, UnsafeOptionError
3638
from git.refs import Reference, RemoteReference, SymbolicReference, TagReference
3739
from git.types import AnyGitObject, Literal, PathLike
3840
from git.util import (
@@ -49,6 +51,7 @@
4951
from git.repo.base import Repo
5052

5153
_T_RemoteName = TypeVar("_T_RemoteName", bound=Union[str, "Remote"])
54+
_PushSource = Tuple[Optional[SymbolicReference], Optional[str]]
5255

5356
flagKeyLiteral = Literal[" ", "!", "+", "-", "*", "=", "t", "?"]
5457

@@ -125,8 +128,8 @@ class PushInfo(IterableObj):
125128
# It is None if the ref was deleted, or if the pushed source
126129
# was not a reference, like a commit hash or HEAD~1.
127130
info.local_hash # Hash of the pushed object if the source was not a
128-
# reference, otherwise None. For new and rejected refs git
129-
# prints no hash, so the source is resolved after the push.
131+
# reference and the hash was reported by Git or could be
132+
# resolved before the push. Otherwise None.
130133
info.remote_ref_string # path to the remote reference located on the remote side
131134
info.remote_ref # Remote Reference on the local side corresponding to
132135
# the remote_ref_string. It can be a TagReference as well.
@@ -222,7 +225,30 @@ def remote_ref(self) -> Union[RemoteReference, TagReference]:
222225
# END
223226

224227
@classmethod
225-
def _from_line(cls, remote: "Remote", line: str) -> "PushInfo":
228+
def _source_ref(
229+
cls, remote: "Remote", source: str, env: Optional[Mapping[str, str]]
230+
) -> Optional[SymbolicReference]:
231+
# Git also prints revision expressions here, including ones under refs/.
232+
if cls._re_revision_syntax.search(source):
233+
return None
234+
try:
235+
ref = Reference.from_path(remote.repo, source)
236+
if env:
237+
remote.repo.git._call_process_safe("show_ref", "--exists", "--", source, env=env)
238+
else:
239+
ref._get_ref_info(remote.repo, source)
240+
except (GitCommandError, ValueError):
241+
return None
242+
return ref
243+
244+
@classmethod
245+
def _from_line(
246+
cls,
247+
remote: "Remote",
248+
line: str,
249+
sources: Optional[Mapping[str, _PushSource]] = None,
250+
env: Optional[Mapping[str, str]] = None,
251+
) -> "PushInfo":
226252
"""Create a new :class:`PushInfo` instance as parsed from line which is expected
227253
to be like refs/heads/master:refs/heads/master 05d2687..1d0568e as bytes."""
228254
control_character, from_to, summary = line.split("\t", 3)
@@ -238,20 +264,12 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo":
238264
# from_to handling
239265
from_ref_string, to_ref_string = from_to.rsplit(":", 1)
240266
from_ref: Union[SymbolicReference, None] = None
241-
is_revision = False
267+
local_hash: Optional[str] = None
242268
if not flags & cls.DELETED and from_ref_string != "(delete)":
243-
# Git prints the source as it was given, which can be any revision.
244-
# from_path() would accept one under refs/, like refs/heads/main~1.
245-
if cls._re_revision_syntax.search(from_ref_string):
246-
is_revision = True
269+
if sources is not None and from_ref_string in sources:
270+
from_ref, local_hash = sources[from_ref_string]
247271
else:
248-
try:
249-
candidate = Reference.from_path(remote.repo, from_ref_string)
250-
candidate._get_ref_info(remote.repo, from_ref_string)
251-
except ValueError:
252-
is_revision = True
253-
else:
254-
from_ref = candidate
272+
from_ref = cls._source_ref(remote, from_ref_string, env)
255273

256274
# Commit handling, could be message or commit info
257275
old_commit: Optional[str] = None
@@ -281,19 +299,20 @@ def _from_line(cls, remote: "Remote", line: str) -> "PushInfo":
281299
old_commit = old_sha
282300
# END message handling
283301

284-
local_hash: Optional[str] = None
285-
if is_revision:
286-
# The push may have moved a ref the revision is relative to, like
287-
# origin/main~1, so prefer the hash git reports as pushed.
288-
try:
289-
if new_sha:
302+
if from_ref is None and new_sha:
303+
# Prefer the object ID reported by the push over the pre-push lookup.
304+
local_hash = None
305+
if remote.repo.re_hexsha_only.fullmatch(new_sha):
306+
local_hash = new_sha
307+
elif env is not None:
308+
try:
290309
# rev-parse would prefer a ref spelled like the abbreviated ID.
291-
oids = remote.repo.git._call_process_safe("rev_parse", "--disambiguate=%s" % new_sha).split()
310+
oids = remote.repo.git._call_process_safe(
311+
"rev_parse", "--disambiguate=%s" % new_sha, env=env
312+
).split()
292313
local_hash = oids[0] if len(oids) == 1 else None
293-
else:
294-
local_hash = remote.repo.rev_parse(from_ref_string).hexsha
295-
except (ODBError, GitCommandError, UnsafeOptionError, ValueError):
296-
pass
314+
except (GitCommandError, UnsafeOptionError, ValueError):
315+
pass
297316

298317
return PushInfo(flags, from_ref, to_ref_string, remote, old_commit, summary, local_hash)
299318

@@ -907,6 +926,9 @@ def _get_push_info(
907926
proc: "Git.AutoInterrupt",
908927
progress: Union[Callable[..., Any], RemoteProgress, None],
909928
kill_after_timeout: Union[None, float] = None,
929+
*,
930+
sources: Optional[Mapping[str, _PushSource]] = None,
931+
env: Optional[Mapping[str, str]] = None,
910932
) -> PushInfoList:
911933
progress = to_progress_instance(progress)
912934

@@ -929,7 +951,7 @@ def _get_push_info(
929951
# Optional lookups are independent of the push's process timeout.
930952
for line in list(push_info_lines):
931953
try:
932-
output.append(PushInfo._from_line(self, line))
954+
output.append(PushInfo._from_line(self, line, sources, env))
933955
except ValueError:
934956
# Non-status lines are handled through stderr and the exit code below.
935957
pass
@@ -948,6 +970,27 @@ def _get_push_info(
948970

949971
return output
950972

973+
def _push_sources(self, refspecs: Sequence[str], env: Mapping[str, str]) -> Dict[str, _PushSource]:
974+
sources: Dict[str, _PushSource] = {}
975+
for refspec in refspecs:
976+
source, separator, _ = refspec.lstrip("+").rpartition(":")
977+
if not separator or not source or source in sources:
978+
continue
979+
ref = PushInfo._source_ref(self, source, env)
980+
oid = None
981+
if ref is None:
982+
try:
983+
Git._check_operand(source, "revision")
984+
resolved = self.repo.git._call_process_safe(
985+
"rev_parse", "--verify", "--quiet", "--end-of-options", source, env=env
986+
)
987+
if self.repo.re_hexsha_only.fullmatch(resolved):
988+
oid = resolved
989+
except (GitCommandError, UnsafeOptionError, ValueError):
990+
pass
991+
sources[source] = ref, oid
992+
return sources
993+
951994
def _assert_refspec(self) -> None:
952995
"""Turns out we can't deal with remotes if the refspec is missing."""
953996
config = self.config_reader
@@ -1199,6 +1242,9 @@ def push(
11991242
unsafe_options=self.unsafe_git_push_options,
12001243
)
12011244

1245+
# Do not consume Git options reserved for the next command.
1246+
env = None if self.repo.git._git_options else kwargs.get("env") or {}
1247+
sources = self._push_sources(refspec, env) if env is not None else None
12021248
proc = self.repo.git._call_process_safe(
12031249
"push",
12041250
"--",
@@ -1211,7 +1257,7 @@ def push(
12111257
kill_after_timeout=kill_after_timeout,
12121258
**kwargs,
12131259
)
1214-
return self._get_push_info(proc, progress, kill_after_timeout=kill_after_timeout)
1260+
return self._get_push_info(proc, progress, kill_after_timeout=kill_after_timeout, sources=sources, env=env)
12151261

12161262
@property
12171263
def config_reader(self) -> SectionConstraint[GitConfigParser]:

‎test/test_remote.py‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,40 @@ def test_push_describe_source_with_ref_prefix(self, rw_repo):
594594
self.assertEqual(info.local_hash, current.hexsha)
595595
self.assertEqual(rw_repo.heads.snapshot.commit, current)
596596

597+
@with_rw_repo("HEAD", bare=False)
598+
def test_push_snapshots_source_before_updating_tracking_ref(self, rw_repo):
599+
remote = rw_repo.create_remote("self", rw_repo.git_dir)
600+
current = rw_repo.head.commit
601+
parent = current.parents[0]
602+
previous_source = parent.parents[0]
603+
remote.push(f"{parent.hexsha}:refs/heads/pushed_ref").raise_if_error()
604+
605+
result = remote.push(["HEAD:refs/heads/pushed_ref", "self/pushed_ref~1:refs/heads/snapshot"])
606+
607+
result.raise_if_error()
608+
infos = {info.remote_ref_string: info for info in result}
609+
self.assertEqual(infos["refs/heads/snapshot"].local_hash, previous_source.hexsha)
610+
self.assertEqual(rw_repo.heads.snapshot.commit, previous_source)
611+
self.assertEqual(rw_repo.commit("refs/remotes/self/pushed_ref"), current)
612+
613+
@with_rw_repo("HEAD", bare=False)
614+
def test_push_resolves_revision_source_with_call_environment(self, rw_repo):
615+
remote = rw_repo.create_remote("self", rw_repo.git_dir)
616+
parent = rw_repo.head.commit.parents[0]
617+
rw_repo.git.replace("HEAD", parent.hexsha)
618+
self.assertEqual(rw_repo.git.rev_parse("HEAD~1"), parent.parents[0].hexsha)
619+
620+
(info,) = remote.push("HEAD~1:refs/heads/snapshot", env={"GIT_NO_REPLACE_OBJECTS": "1"})
621+
622+
self.assertIsNone(info.local_ref)
623+
self.assertEqual(info.local_hash, parent.hexsha)
624+
self.assertEqual(rw_repo.heads.snapshot.commit, parent)
625+
626+
rw_repo.git(no_replace_objects=True)
627+
(info,) = remote.push("HEAD~1:refs/heads/snapshot_once")
628+
self.assertIsNone(info.local_hash)
629+
self.assertEqual(rw_repo.heads.snapshot_once.commit, parent)
630+
597631
@with_rw_repo("HEAD", bare=False)
598632
def test_push_revision_sources(self, rw_repo):
599633
remote = rw_repo.create_remote("self", rw_repo.git_dir)
@@ -634,14 +668,19 @@ def test_push_revision_sources(self, rw_repo):
634668
self.assertIsNone(info.local_ref)
635669
self.assertEqual(info.local_hash, parent.hexsha)
636670

671+
run = Git._call_process_safe
672+
673+
def fail_revision(git, method, *args, **kwargs):
674+
if method == "rev_parse" and args == ("--verify", "--quiet", "--end-of-options", "HEAD~1"):
675+
raise GitCommandError("rev-parse", 128)
676+
return run(git, method, *args, **kwargs)
677+
637678
# A failed lookup keeps the result without a hash.
638-
with mock.patch.object(rw_repo, "rev_parse", side_effect=GitCommandError("rev-parse", 128)):
679+
with mock.patch.object(Git, "_call_process_safe", fail_revision):
639680
(info,) = remote.push("HEAD~1:refs/heads/pushed_lookup")
640681
self.assertTrue(info.flags & PushInfo.NEW_HEAD)
641682
self.assertIsNone(info.local_hash)
642683

643-
run = Git._call_process_safe
644-
645684
def fail_disambiguate(git, method, *args, **kwargs):
646685
if method == "rev_parse" and args and str(args[0]).startswith("--disambiguate="):
647686
raise GitCommandError("rev-parse", 128)
@@ -1231,7 +1270,7 @@ def track_disambiguate(git, method, *args, **kwargs):
12311270
return run(git, method, *args, **kwargs)
12321271

12331272
with mock.patch.object(Git, "_call_process_safe", track_disambiguate):
1234-
result = repo.remote("origin")._get_push_info(process, None, kill_after_timeout=5)
1273+
result = repo.remote("origin")._get_push_info(process, None, kill_after_timeout=5, env={})
12351274

12361275
result.raise_if_error()
12371276
assert stream_closed == [True]

0 commit comments

Comments
 (0)