Skip to content

Commit c327590

Browse files
codexByron
authored andcommitted
fix(submodule): honor branch overrides in superproject config
When `.gitmodules` sets `branch = .`, Git takes an explicit `submodule.<name>.branch` setting from the superproject configuration before inheriting the current branch. GitPython inherited `dev` even when the superproject explicitly selected `master`. Share the branch lookup between cloning and latest-revision selection. Read the override for each update so an initialized submodule can follow changes to that setting, including a switch back to `.`. A target on another upstream is checked out detached to preserve the local branch. Use the existing Gix scalar config adapter for text keys. Fall back to Git for non-UTF-8 keys, which GixPython 0.3.0 cannot accept, and record the limitation in `doc/gix-backend.md`. The override regression failed on both backends before the fix. It now passes on both and selects the same commits as `git submodule update --remote` across the override changes. The byte-key config regression also passes on both backends. Agent-Model: gpt-6.2-sol Agent-Reasoning-Effort: high
1 parent a03950f commit c327590

5 files changed

Lines changed: 65 additions & 16 deletions

File tree

‎doc/gix-backend.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1180,6 +1180,12 @@ retain GitPython's configuration contract natively. The scripted
11801180
`submodule-bytes.sh` regressions cover values, names and cached-field rereads;
11811181
the native value test prohibits CLI execution.
11821182

1183+
Repository `config --get` also uses Git for byte keys. Git 2.54.0 can read a raw
1184+
key such as `remote.origin-<ff>.url`, while GixPython 0.3.0 raises
1185+
`UnicodeEncodeError` for its surrogate-escaped form. The scalar lookup in
1186+
`test_config_preserves_non_utf8_subsections_and_values` exercises this
1187+
fallback, which also applies to submodule branch overrides.
1188+
11831189
The October 7 inventory identified 951 remote-enumeration reads, 674 actor
11841190
lookups, 262 remote-property reads, 202 tracking-branch lookups and 111 fetch
11851191
refspec checks. These are historical call-site counts, not additive savings.

‎git/_backend.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,10 @@ def submodule_config(source: Any) -> Any:
471471
def _config(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes:
472472
if len(args) == 2 and args[0] == "--get":
473473
snapshot = repo.config_snapshot()
474-
value = snapshot.string(args[1])
474+
try:
475+
value = snapshot.string(args[1])
476+
except UnicodeEncodeError as exc:
477+
raise _Unsupported("non-UTF-8 configuration key (GIX-12)") from exc
475478
if value is None:
476479
if snapshot.boolean(args[1]) is None:
477480
raise GitCommandError(["git", "config"], 1)

‎git/objects/submodule/base.py‎

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
Literal,
2727
Mapping,
2828
Sequence,
29+
Tuple,
2930
Union,
3031
cast,
3132
)
@@ -901,9 +902,10 @@ def update(
901902
the remote will be fetched, and the local tracking branch updated. This only
902903
works if we have a local tracking branch, which is the case if the remote
903904
repository had a master branch, or if the ``branch`` option was specified
904-
for this submodule and the branch existed remotely. With ``branch = .``
905-
and an active superproject branch, the submodule follows the remote branch
906-
of the same name and checks it out detached if it differs from the upstream.
905+
for this submodule and the branch existed remotely. A superproject config
906+
override selects the target branch. With ``branch = .`` and an active
907+
superproject branch, the submodule follows the remote branch of the same
908+
name. If the selected branch differs from the upstream, the checkout is detached.
907909
908910
:param progress:
909911
:class:`UpdateProgress` instance, or ``None`` if no progress should be
@@ -981,6 +983,7 @@ def update(
981983

982984
mrepo = None
983985
freshly_cloned = False
986+
update_branch = None
984987
# END init mrepo
985988

986989
def fetch_remotes(module_repo: "Repo") -> None:
@@ -1099,22 +1102,20 @@ def fetch_remotes(module_repo: "Repo") -> None:
10991102

11001103
if not dry_run:
11011104
# See whether we have a valid branch to check out.
1102-
branch_path = git.Head.to_full_path(self.branch_path)
1103-
# gitmodules(5): branch "." names the superproject's current branch.
1104-
if branch_path == git.Head.to_full_path(".") and not self.repo.head.is_detached:
1105-
branch_path = self.repo.head.reference.path
1105+
update_branch = self._branch_for_update()
1106+
branch, _ = update_branch
11061107
try:
11071108
mrepo = cast("Repo", mrepo)
1108-
remote_branch = find_first_remote_branch(mrepo.remotes, git.Head(mrepo, branch_path).name)
1109-
local_branch = mkhead(mrepo, branch_path)
1109+
remote_branch = find_first_remote_branch(mrepo.remotes, branch.name)
1110+
local_branch = mkhead(mrepo, branch.path)
11101111
local_branch.set_object(remote_branch.commit)
11111112
mrepo.head.set_reference(
11121113
local_branch,
11131114
logmsg="submodule: attaching head to %s" % local_branch,
11141115
)
11151116
mrepo.head.reference.set_tracking_branch(remote_branch)
11161117
except (IndexError, InvalidGitRepositoryError):
1117-
_logger.warning("Failed to checkout tracking branch %s", branch_path)
1118+
_logger.warning("Failed to checkout tracking branch %s", branch.path)
11181119

11191120
with self.repo.config_writer() as writer:
11201121
writer.set_value(sm_section(self.name), "url", self.url)
@@ -1135,12 +1136,10 @@ def fetch_remotes(module_repo: "Repo") -> None:
11351136
msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir
11361137
upstream = None if checkout_detached else mrepo.active_branch.tracking_branch()
11371138
rref = upstream
1138-
if (
1139-
git.Head.to_full_path(self.branch_path) == git.Head.to_full_path(".")
1140-
and not self.repo.head.is_detached
1141-
):
1139+
branch, use_configured_branch = update_branch or self._branch_for_update()
1140+
if use_configured_branch:
11421141
remote = upstream.remote_name if isinstance(upstream, git.RemoteReference) else "origin"
1143-
rref = git.RemoteReference(mrepo, f"refs/remotes/{remote}/{self.repo.active_branch.name}")
1142+
rref = git.RemoteReference(mrepo, f"refs/remotes/{remote}/{branch.name}")
11441143
# Keep the local branch pointing at its own history when following another branch.
11451144
checkout_detached = rref != upstream
11461145

@@ -1826,6 +1825,23 @@ def branch_name(self) -> str:
18261825
# uses a repository that is available at least (it makes no difference).
18271826
return git.Head(self.repo, self._branch_path).name
18281827

1828+
def _branch_for_update(self) -> Tuple["Head", bool]:
1829+
"""Return the clone branch and whether it selects the latest revision."""
1830+
key = f"submodule.{self.name}.{self.k_head_option}"
1831+
try:
1832+
override = self.repo.git._call_process_safe("config", "--get", key)
1833+
except GitCommandError as exc:
1834+
if exc.status != 1:
1835+
raise
1836+
override = None
1837+
1838+
branch = mkhead(self.repo, self.branch_path if override is None else override)
1839+
if branch.name != ".":
1840+
return branch, override is not None
1841+
if not self.repo.head.is_detached:
1842+
return self.repo.active_branch, True
1843+
return branch, False
1844+
18291845
@property
18301846
def url(self) -> str:
18311847
""":return: The url to the repository our submodule's repository refers to"""

‎test/test_config.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ def test_config_preserves_non_utf8_subsections_and_values(stream):
8585
remote = repo.remotes[0]
8686
assert remote.name == "origin-\udcff"
8787
assert remote.url == "target-\udcfe"
88+
if os.name != "nt":
89+
assert repo.git._call_process_safe("config", "--get", "remote.origin-\udcff.url") == "target-\udcfe"
8890

8991

9092
@pytest.mark.skipif(os.name == "nt", reason="Windows command arguments cannot carry arbitrary bytes")

‎test/test_submodule.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1986,6 +1986,28 @@ def test_update_to_latest_revision_after_superproject_switch(self):
19861986
with submodule.module() as module:
19871987
assert module.head.commit == source.heads.dev.commit
19881988

1989+
@patch_git_config("protocol.file.allow", "always")
1990+
def test_update_to_latest_revision_respects_local_branch_override(self):
1991+
# The submodule URL points to this private fixture's source.
1992+
rwdir = self._fixture("branch-dot", execute=True)
1993+
with git.Repo(rwdir / "source") as source, git.Repo(rwdir / "clone") as parent:
1994+
submodule = parent.submodules[0]
1995+
parent.git.config("--local", "submodule.module.branch", "master")
1996+
submodule.update(to_latest_revision=True)
1997+
with submodule.module() as module:
1998+
assert module.active_branch.name == "master"
1999+
assert module.head.commit == source.heads.master.commit
2000+
2001+
parent.git.config("--local", "submodule.module.branch", ".")
2002+
submodule.update(to_latest_revision=True, no_fetch=True)
2003+
with submodule.module() as module:
2004+
assert module.head.commit == source.heads.dev.commit
2005+
2006+
parent.git.config("--local", "submodule.module.branch", "master")
2007+
submodule.update(to_latest_revision=True, no_fetch=True)
2008+
with submodule.module() as module:
2009+
assert module.head.commit == source.heads.master.commit
2010+
19892011
@patch_git_config("protocol.file.allow", "always")
19902012
def test_update_to_latest_revision_after_reread_follows_named_branch(self):
19912013
rwdir = self._fixture("branch-dot", execute=True)

0 commit comments

Comments
 (0)