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
56 changes: 43 additions & 13 deletions git/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
NoReturn,
Optional,
Sequence,
Set,
TypeVar,
Union,
cast,
Expand Down Expand Up @@ -371,7 +372,13 @@ def _display_ref(path: str) -> str:
return path

@classmethod
def _from_line(cls, repo: "Repo", line: str, refspecs: Sequence[str] = (), refs: Sequence[str] = ()) -> "FetchInfo":
def _from_line(
cls,
repo: "Repo",
line: str,
refspecs: Sequence[str] = (),
refs_by_display: Optional[Dict[str, Set[str]]] = None,
) -> "FetchInfo":
"""Decode Git's full verbose fetch output without reading FETCH_HEAD."""
match = cls._re_fetch_result.match(line)
if match is None:
Expand All @@ -394,26 +401,46 @@ def _from_line(cls, repo: "Repo", line: str, refspecs: Sequence[str] = (), refs:
if destination == "FETCH_HEAD":
ref = SymbolicReference(repo, destination)
else:
# Git's "new" status describes the source namespace.
if flags & cls.NEW_TAG:
wildcard_sources = ["refs/tags/" + source]
elif flags & cls.NEW_HEAD:
wildcard_sources = ["refs/heads/" + source]
else:
wildcard_sources = ["refs/remotes/" + source]
if operation != "[new ref]":
wildcard_sources.extend(("refs/heads/" + source, "refs/tags/" + source))
if cls._display_ref(source) == source:
wildcard_sources.append(source)

candidates = set()
for spec in refspecs:
if spec.startswith("^") or ":" not in spec:
continue
remote, local = spec.lstrip("+").split(":", 1)
remote = cls._display_ref(remote)
if "*" in remote:
prefix, suffix = remote.split("*", 1)
if not source.startswith(prefix) or not source.endswith(suffix):
continue
middle = source[len(prefix) : len(source) - len(suffix) if suffix else None]
local = local.replace("*", middle)
elif remote != source:
continue
if cls._display_ref(local) == destination:
for path in wildcard_sources:
if not path.startswith(prefix) or not path.endswith(suffix):
continue
middle = path[len(prefix) : len(path) - len(suffix) if suffix else None]
mapped = local.replace("*", middle)
if cls._display_ref(mapped) == destination:
candidates.add(mapped)
elif (
source in (cls._display_ref(remote), cls._display_ref("refs/" + remote))
and cls._display_ref(local) == destination
):
candidates.add(local)
if destination.startswith("refs/"):
candidates = {destination}
matching_refs = refs_by_display.get(destination, ()) if refs_by_display is not None else ()
if (control == "=" or old_commit is not None) and len(candidates) > 1:
candidates.intersection_update(matching_refs)
if not candidates:
candidates = {path for path in refs if cls._display_ref(path) == destination}
candidates.update(matching_refs)
# Git shortens refs/tags/refs/heads/main to refs/heads/main, so a
# displayed name under refs/ is only a full name if nothing shortens to it.
if not candidates and destination.startswith("refs/"):
candidates = {destination}
if len(candidates) > 1 and ("tag" in operation or control == "t"):
candidates = {path for path in candidates if path.startswith("refs/tags/")}
if len(candidates) != 1:
Expand Down Expand Up @@ -820,14 +847,17 @@ def _get_fetch_info_from_stderr(
continue

refs = self.repo.git._call_process_safe("for_each_ref", "--format=%(refname)").split("\n")
refs_by_display: Dict[str, Set[str]] = {}
for path in refs:
refs_by_display.setdefault(FetchInfo._display_ref(path), set()).add(path)
try:
configured = self.config_reader.config.get_values(self._config_section_name(), "fetch")
except (cp.NoSectionError, cp.NoOptionError):
configured = []
specs = [*refspecs, *configured]
for line in fetch_info_lines:
try:
output.append(FetchInfo._from_line(self.repo, line, specs, refs))
output.append(FetchInfo._from_line(self.repo, line, specs, refs_by_display))
except ValueError as exc:
_logger.warning("Cannot decode fetch result %r: %s", line, exc)
# A source-only refspec reports both FETCH_HEAD and any opportunistic
Expand Down
45 changes: 45 additions & 0 deletions test/test_remote_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,51 @@ def checked_open(path, *args, **kwargs):
clone.close()


@pytest.mark.parametrize("remote_fixture", [("tag-named-like-branch",)], indirect=True)
def test_fetch_resolves_tag_named_like_a_full_branch_ref(remote_fixture):
# Git displays refs/tags/refs/heads/main as refs/heads/main.
with Repo(remote_fixture / "source") as source, Repo(remote_fixture / "clone") as clone:
branch = clone.heads.main.commit
[info] = [info for info in clone.remote().fetch() if info.flags & FetchInfo.NEW_TAG]
assert info.ref.path == "refs/tags/refs/heads/main"
assert info.commit == source.head.commit
assert clone.heads.main.commit == branch


@pytest.mark.parametrize("remote_fixture", [("abbreviated-tag-source",)], indirect=True)
def test_fetch_resolves_explicit_destination_that_looks_like_a_local_tag(remote_fixture):
with Repo(remote_fixture / "source") as source, Repo(remote_fixture / "clone") as clone:
[info] = clone.remote().fetch("tags/v1:refs/archive/v1", no_tags=True)
assert info.ref.path == "refs/archive/v1"
assert info.commit == source.head.commit
assert clone.tags["refs/archive/v1"].commit == clone.head.commit


@pytest.mark.parametrize("remote_fixture", [("notes-and-tag-wildcards",)], indirect=True)
def test_fetch_resolves_notes_with_a_tag_wildcard(remote_fixture):
with Repo(remote_fixture / "source") as source, Repo(remote_fixture / "clone") as clone:
remote = clone.remote()
for flags in (0, FetchInfo.HEAD_UPTODATE, FetchInfo.FAST_FORWARD):
if flags == FetchInfo.FAST_FORWARD:
source.git.update_ref("refs/notes/commits", "refs/fixture/updated-notes")
[info] = [info for info in remote.fetch() if info.remote_ref_path == "refs/notes/commits"]
assert info.ref.path == "refs/notes/commits"
assert info.commit == source.commit("refs/notes/commits")
assert info.flags == flags


@pytest.mark.parametrize("remote_fixture", [("prefetch",)], indirect=True)
def test_prefetch_indexes_displayed_refs_once(remote_fixture):
paths = {"refs/prefetch/remotes/origin/main", "refs/prefetch/remotes/origin/second"}
with Repo(remote_fixture / "clone") as clone:
with mock.patch.object(FetchInfo, "_display_ref", wraps=FetchInfo._display_ref) as display_ref:
result = clone.remote().fetch(prefetch=True)
assert {info.ref.path for info in result} == paths
assert all(info.flags == FetchInfo.HEAD_UPTODATE for info in result)
displayed = [args[0] for args, _ in display_ref.call_args_list if args[0] in paths]
assert len(displayed) == len(set(displayed))


@pytest.mark.parametrize("remote_fixture", [("quoted",)], indirect=True)
def test_quoted_remote_and_submodule_names(remote_fixture):
tmp_path = remote_fixture
Expand Down
31 changes: 31 additions & 0 deletions tests/fixtures/remote-cli.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,37 @@ case "$1" in
git -C clone remote set-url origin ../source
git -C source commit --allow-empty -m second
;;
tag-named-like-branch)
git clone source clone
git -C clone remote set-url origin ../source
git -C source commit --allow-empty -m second
git -C source tag refs/heads/main
;;
abbreviated-tag-source)
git clone source clone
git -C clone remote set-url origin ../source
git -C clone tag refs/archive/v1
git -C source commit --allow-empty -m second
git -C source tag v1
;;
notes-and-tag-wildcards)
git clone source clone
git -C clone remote set-url origin ../source
git -C clone config --unset-all remote.origin.fetch
git -C clone config --add remote.origin.fetch '+refs/notes/*:refs/notes/*'
git -C clone config --add remote.origin.fetch '+refs/tags/*:refs/tags/*'
git -C source notes add -m 'a note'
initial_notes=$(git -C source rev-parse refs/notes/commits)
git -C source notes append -m 'more notes'
git -C source update-ref refs/fixture/updated-notes refs/notes/commits
git -C source update-ref refs/notes/commits "$initial_notes"
;;
prefetch)
git -C source branch second
git clone source clone
git -C clone remote set-url origin ../source
git -C clone fetch --prefetch
;;
quoted)
git init --initial-branch=main parent
;;
Expand Down
Loading