diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 04a5ef2ce..821272bf7 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -71,7 +71,7 @@ from git.types import TBD, Commit_ish, PathLike if TYPE_CHECKING: - from git.index import IndexFile + from git.index import IndexEntry, IndexFile from git.objects.commit import Commit from git.refs import Head from git.repo import Repo @@ -2021,6 +2021,10 @@ def iter_items( native = _backend.submodule_config(parser._file_or_files) sections = parser.sections() if native is NotImplemented else [sm_section(name) for name in native] + # Both repository lookups below are the same for every section, so read each + # of them at most once instead of once per section. + entries: Union[Mapping[Tuple[PathLike, int], "IndexEntry"], None] = None + head_commit: Union["Commit", None] = None for sms in sections: n = sm_name(sms) if native is NotImplemented: @@ -2032,20 +2036,19 @@ def iter_items( b = native[n].get(cls.k_head_option, cls.k_head_default) # Get the binsha. - index = repo.index try: rt = pc.tree # Root tree sm = rt[p] except KeyError: - # Try the index, maybe it was just added. - try: - entry = index.entry(p) - sm = Submodule(repo, entry.binsha, entry.mode, entry.path) - except KeyError: + # Try the index, maybe it was just added. One read serves every section. + if entries is None: + entries = repo.index.entries + entry = entries.get((p, 0)) + if entry is None: # The submodule doesn't exist, probably it wasn't removed from the # .gitmodules file. continue - # END handle keyerror + sm = Submodule(repo, entry.binsha, entry.mode, entry.path) # END handle critical error # Make sure we are looking at a submodule object. @@ -2054,7 +2057,9 @@ def iter_items( # Fill in remaining info - saves time as it doesn't have to be parsed again. sm._name = n - if pc != repo.commit(): + if head_commit is None: + head_commit = repo.commit() + if pc != head_commit: sm._parent_commit = pc # END set only if not most recent! sm._branch_path = git.Head.to_full_path(b) diff --git a/test/test_submodule.py b/test/test_submodule.py index 29a3483cc..a0392fcb9 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -6,6 +6,7 @@ import os import os.path as osp from pathlib import Path, PurePosixPath +import re import shutil import sys from types import SimpleNamespace @@ -81,6 +82,35 @@ def test_submodule_configuration_preserves_non_utf8_bytes(scenario, name): ) +def _backend_operations(): + """Count repository operations, whichever backend carries them out.""" + return sum(git._backend.statistics().values()) + + +@pytest.mark.parametrize("location", ["in-tree", "in-index", "absent"]) +def test_listing_submodules_queries_the_repository_once(location): + with fixture_repo("submodule-many.sh", write=True) as repo: + config = Path(repo.working_tree_dir, ".gitmodules") + sections = re.findall(r"\[submodule[^[]*", config.read_text()) + assert len(sections) == 12 + paths = ["module%02d" % index for index in range(len(sections))] + if location != "in-tree": + paths = ["%s/%s" % (location, path) for path in paths] + sections = [section.replace("path = module", "path = %s/module" % location) for section in sections] + if location == "in-index": + specs = ["160000,%s,%s" % (repo.head.commit.hexsha, path) for path in paths] + repo.git.update_index("--add", *[argument for spec in specs for argument in ("--cacheinfo", spec)]) + + def list_submodules(count): + config.write_text("".join(sections[:count])) + before = _backend_operations() + assert len(repo.submodules) == (0 if location == "absent" else count) + return _backend_operations() - before + + list_submodules(1) # Warm the caches a first listing fills. + assert list_submodules(12) == list_submodules(1) + + @pytest.mark.skipif(git._backend.name != "gix", reason="requires the native backend") def test_native_submodule_configuration_preserves_non_utf8_values(): path = read_only_fixture("submodule-bytes.sh", "ascii-name") / "repo" / ".gitmodules" diff --git a/tests/fixtures/submodule-many.sh b/tests/fixtures/submodule-many.sh new file mode 100644 index 000000000..9458e7f0f --- /dev/null +++ b/tests/fixtures/submodule-many.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -eu +export GIT_AUTHOR_NAME='GitPython Tests' GIT_AUTHOR_EMAIL='tests@example.invalid' +export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL" +export GIT_AUTHOR_DATE='2001-01-01T00:00:00 +0000' +export GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" +git init -q -b master repo +cd repo +git commit --allow-empty -qm 'Initial commit' +oid=$(git rev-parse HEAD) +for index in 0 1 2 3 4 5 6 7 8 9 10 11; do + name=$(printf 'module%02d' "$index") + git update-index --add --cacheinfo "160000,$oid,$name" + printf '[submodule "%s"]\npath = %s\nurl = ../%s\n' "$name" "$name" "$name" >>.gitmodules +done +git add .gitmodules +git commit -qm 'Add submodules'