Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/source/changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ API changes
current repository (``branch.<name>.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.
Expand Down
49 changes: 40 additions & 9 deletions git/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 GitCommandError, ODBError
from git.refs import Reference, RemoteReference, SymbolicReference, TagReference
from git.types import AnyGitObject, Literal, PathLike
from git.util import (
Expand Down Expand Up @@ -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.
Expand All @@ -132,6 +137,7 @@ class PushInfo(IterableObj):

__slots__ = (
"local_ref",
"local_hash",
"remote_ref_string",
"flags",
"_old_commit_sha",
Expand Down Expand Up @@ -165,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,
Expand All @@ -173,13 +182,15 @@ def __init__(
remote: "Remote",
old_commit: Optional[str] = None,
summary: str = "",
local_hash: Optional[str] = None,
) -> None:
"""Initialize a new instance.

local_ref: HEAD | Head | RemoteReference | TagReference | Reference | SymbolicReference | None
"""
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
Expand Down Expand Up @@ -226,16 +237,22 @@ 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
from_ref: Union[SymbolicReference, None] = None
is_revision = False
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
else:
from_ref = Reference.from_path(remote.repo, from_ref_string)
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
new_sha: Optional[str] = None
if summary.startswith("["):
if "[rejected]" in summary:
flags |= cls.REJECTED
Expand All @@ -256,12 +273,26 @@ 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:
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)

@classmethod
def iter_items(cls, repo: "Repo", *args: Any, **kwargs: Any) -> NoReturn: # -> Iterator['PushInfo']:
Expand Down
59 changes: 59 additions & 0 deletions test/test_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,65 @@ 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)

# 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"
Expand Down
Loading