diff --git a/doc/gix-backend.md b/doc/gix-backend.md index f2ad15dcb..c9d64870f 100644 --- a/doc/gix-backend.md +++ b/doc/gix-backend.md @@ -383,8 +383,9 @@ 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 | | 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 | @@ -1019,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/doc/source/changes.rst b/doc/source/changes.rst index e264c8056..cca7195da 100644 --- a/doc/source/changes.rst +++ b/doc/source/changes.rst @@ -115,6 +115,15 @@ 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 + 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/_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/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 4b470b5f0..9a87b558e 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,6 +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, UnsafeOptionError from git.refs import Reference, RemoteReference, SymbolicReference, TagReference from git.types import AnyGitObject, Literal, PathLike from git.util import ( @@ -48,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", "?"] @@ -121,7 +125,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 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. @@ -132,6 +140,7 @@ class PushInfo(IterableObj): __slots__ = ( "local_ref", + "local_hash", "remote_ref_string", "flags", "_old_commit_sha", @@ -165,6 +174,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, @@ -173,6 +185,7 @@ def __init__( remote: "Remote", old_commit: Optional[str] = None, summary: str = "", + local_hash: Optional[str] = None, ) -> None: """Initialize a new instance. @@ -180,6 +193,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 @@ -211,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) @@ -225,17 +262,18 @@ 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(":") - if flags & cls.DELETED: - from_ref: Union[SymbolicReference, None] = None - else: - if from_ref_string == "(delete)": - from_ref = None + from_ref_string, to_ref_string = from_to.rsplit(":", 1) + from_ref: Union[SymbolicReference, None] = None + local_hash: Optional[str] = None + if not flags & cls.DELETED and from_ref_string != "(delete)": + if sources is not None and from_ref_string in sources: + from_ref, local_hash = sources[from_ref_string] else: - from_ref = Reference.from_path(remote.repo, from_ref_string) + from_ref = cls._source_ref(remote, from_ref_string, env) # 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 +294,27 @@ 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) + 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 + else: + 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, env=env + ).split() + local_hash = oids[0] if len(oids) == 1 else None + except (GitCommandError, UnsafeOptionError, 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']: @@ -873,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) @@ -882,22 +938,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, sources, env)) + 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) @@ -913,6 +970,27 @@ def stdout_handler(line: str) -> None: 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 @@ -1164,6 +1242,8 @@ def push( unsafe_options=self.unsafe_git_push_options, ) + env = kwargs.get("env") or {} + sources = self._push_sources(refspec, env) proc = self.repo.git._call_process_safe( "push", "--", @@ -1176,7 +1256,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_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 ba18dce3a..8ecf40b6f 100644 --- a/test/test_remote.py +++ b/test/test_remote.py @@ -554,6 +554,145 @@ 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_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_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_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) + + # Discarding the configured wrapper must not affect the push. + rw_repo.git(no_replace_objects=True) + (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): + 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) + + 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(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) + + 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" @@ -1111,6 +1250,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, env={}) + + 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): 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