Skip to content
Closed
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
23 changes: 14 additions & 9 deletions git/objects/submodule/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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.
Expand All @@ -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)
Expand Down
30 changes: 30 additions & 0 deletions test/test_submodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
17 changes: 17 additions & 0 deletions tests/fixtures/submodule-many.sh
Original file line number Diff line number Diff line change
@@ -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'
Loading