From 1dfe4e25901156fd934252da1b7d0a01f76d8251 Mon Sep 17 00:00:00 2001 From: JROtto5 <222316562+JROtto5@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:07:56 -0500 Subject: [PATCH 1/5] fix(submodule): resolve `branch = .` when update() clones a submodule gitmodules(5) defines `submodule..branch = .` as "the same name as the superproject's current branch". With the superproject on `dev`, `git submodule update --init --remote` checks out the submodule's `dev` tip. When update() cloned such a submodule it looked for a remote branch literally named `.` and never found it: from `repo.submodules` it logged "Failed to checkout tracking branch refs/heads/." and stayed on the remote's default branch, so `to_latest_revision=True` moved the submodule to the wrong tip; after `set_parent_commit()` the branch is re-read without the refs/heads/ prefix and `branch_name` raised ValueError instead, for a named branch such as `dev` as well as `.`. Normalize the configured branch to a full ref first, then resolve `refs/heads/.` to the superproject's active branch before the remote-branch lookup. A detached superproject keeps the previous behaviour (the lookup fails and the warning is logged); git refuses in that case. Already-cloned submodules are not touched: update() follows their existing tracking branch, as before. The new `branch-dot` fixture puts the superproject clone on `dev`. `test_update_to_latest_revision_follows_superproject_branch` covers the `repo.submodules` path and the re-read path, and `test_update_to_latest_revision_after_reread_follows_named_branch` the re-read of `dev`; both fail without this change under the `cli` and `gix` backends and pass with it. A third test pins the detached case. Agent-Model: claude-opus-5-5 --- git/objects/submodule/base.py | 10 +++++-- test/test_submodule.py | 48 +++++++++++++++++++++++++++++++ tests/fixtures/submodule-cases.sh | 15 ++++++++++ 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 615b9b777..7a5e2f92b 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -1097,10 +1097,14 @@ def fetch_remotes(module_repo: "Repo") -> None: if not dry_run: # See whether we have a valid branch to check out. + branch_path = git.Head.to_full_path(self.branch_path) + # gitmodules(5): branch "." names the superproject's current branch. + if branch_path == git.Head.to_full_path(".") and not self.repo.head.is_detached: + branch_path = self.repo.head.reference.path try: mrepo = cast("Repo", mrepo) - remote_branch = find_first_remote_branch(mrepo.remotes, self.branch_name) - local_branch = mkhead(mrepo, self.branch_path) + remote_branch = find_first_remote_branch(mrepo.remotes, git.Head(mrepo, branch_path).name) + local_branch = mkhead(mrepo, branch_path) local_branch.set_object(remote_branch.commit) mrepo.head.set_reference( local_branch, @@ -1108,7 +1112,7 @@ def fetch_remotes(module_repo: "Repo") -> None: ) mrepo.head.reference.set_tracking_branch(remote_branch) except (IndexError, InvalidGitRepositoryError): - _logger.warning("Failed to checkout tracking branch %s", self.branch_path) + _logger.warning("Failed to checkout tracking branch %s", branch_path) with self.repo.config_writer() as writer: writer.set_value(sm_section(self.name), "url", self.url) diff --git a/test/test_submodule.py b/test/test_submodule.py index f293e8742..146dc8b55 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -1943,6 +1943,54 @@ def test_update_to_latest_revision_after_deinit_fetches_remote(self): assert submodule.module().head.commit == source_repo.head.commit assert osp.isfile(osp.join(submodule.abspath, "new-file")) + @patch_git_config("protocol.file.allow", "always") + def test_update_to_latest_revision_follows_superproject_branch(self): + for reread in (False, True): + with self.subTest(reread=reread): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + source_repo = git.Repo(rwdir / "source") + parent_repo = git.Repo(rwdir / "clone") + submodule = parent_repo.submodules[0] + if reread: + # Re-reads the branch from .gitmodules as ".", not "refs/heads/.". + submodule.set_parent_commit(parent_repo.head.commit) + + submodule.update(to_latest_revision=True) + + assert submodule.module().active_branch.name == "dev" + assert submodule.module().head.commit == source_repo.heads.dev.commit + + @patch_git_config("protocol.file.allow", "always") + def test_update_to_latest_revision_after_reread_follows_named_branch(self): + rwdir = self._fixture("branch-dot", execute=True) + source_repo = git.Repo(rwdir / "source") + parent_repo = git.Repo(rwdir / "clone") + parent_repo.git.config("-f", ".gitmodules", "submodule.module.branch", "dev") + parent_repo.index.add([".gitmodules"]) + parent_repo.index.commit("Track dev", skip_hooks=True) + submodule = parent_repo.submodules[0] + # Re-reads the branch from .gitmodules as "dev", not "refs/heads/dev". + submodule.set_parent_commit(parent_repo.head.commit) + + submodule.update(to_latest_revision=True) + + assert submodule.module().active_branch.name == "dev" + assert submodule.module().head.commit == source_repo.heads.dev.commit + + @patch_git_config("protocol.file.allow", "always") + def test_update_branch_dot_with_detached_superproject_warns(self): + rwdir = self._fixture("branch-dot", execute=True) + parent_repo = git.Repo(rwdir / "clone") + parent_repo.head.set_reference(parent_repo.head.commit) + submodule = parent_repo.submodules[0] + + # git refuses here too: there is no superproject branch to follow. + with self.assertLogs("git.objects.submodule.base", "WARNING") as logs: + submodule.update(to_latest_revision=True) + + assert any("Failed to checkout tracking branch refs/heads/." in line for line in logs.output) + @patch_git_config("protocol.file.allow", "always") def test_update_after_deinit_fetches_new_gitlink_commit(self): rwdir = self._fixture("deinit-gitlink", execute=True) diff --git a/tests/fixtures/submodule-cases.sh b/tests/fixtures/submodule-cases.sh index 873dafcfa..3a25bc2ec 100644 --- a/tests/fixtures/submodule-cases.sh +++ b/tests/fixtures/submodule-cases.sh @@ -46,6 +46,21 @@ case "$scenario" in deinit-nonempty) printf '%s' 'user content' > parent/module/file ;; esac ;; + branch-dot) + git init -q -b master source + git -C source commit --allow-empty -qm initial + git -C source branch dev + git -C source commit --allow-empty -qm 'Advance master' + git -C source checkout -q dev + git -C source commit --allow-empty -qm 'Advance dev' + git -C source checkout -q master + source="$root/source" + add_module module module + git -C parent config -f .gitmodules submodule.module.branch . + git -C parent commit -qam 'Track the superproject branch' + git -C parent branch dev + git clone -q -b dev parent clone + ;; add-empty) git init -q -b master empty-repo ;; relative) git init -q -b master module From a03950f2c9ba6a15b585fa165c72ddf8cf1d9aed Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 16:40:44 +0100 Subject: [PATCH 2/5] fix(submodule): follow the current superproject branch on update When a submodule with `branch = .` was cloned on `dev`, subsequent `update(to_latest_revision=True)` calls kept using `origin/dev` after the superproject switched to `master`. The branch selection only resolved `.` during cloning. Resolve the remote-tracking ref from the current superproject branch when selecting the latest revision. If the selected ref differs from the submodule's upstream, check out its commit detached to preserve the local branch. The regression switches the superproject from `dev` to `master`, fetches a newer `master` commit, and switches back using cached refs. It failed before the fix and passes with the CLI and Gix backends. Git's `submodule update --remote` selects the same commits. Agent-Model: gpt-6.2-sol Agent-Reasoning-Effort: high --- git/objects/submodule/base.py | 47 ++++++++++++++++++++--------------- test/test_submodule.py | 25 +++++++++++++++++++ 2 files changed, 52 insertions(+), 20 deletions(-) diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 7a5e2f92b..73724aaab 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -901,7 +901,9 @@ def update( the remote will be fetched, and the local tracking branch updated. This only works if we have a local tracking branch, which is the case if the remote repository had a master branch, or if the ``branch`` option was specified - for this submodule and the branch existed remotely. + for this submodule and the branch existed remotely. With ``branch = .`` + and an active superproject branch, the submodule follows the remote branch + of the same name and checks it out detached if it differs from the upstream. :param progress: :class:`UpdateProgress` instance, or ``None`` if no progress should be @@ -1122,31 +1124,36 @@ def fetch_remotes(module_repo: "Repo") -> None: ############################# binsha = self.binsha hexsha = self.hexsha - is_detached = False + checkout_detached = False if mrepo is not None: # mrepo is only set if we are not in dry-run mode or if the module # existed. - is_detached = mrepo.head.is_detached + checkout_detached = mrepo.head.is_detached # END handle dry_run if mrepo is not None and to_latest_revision: msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir - if not is_detached: - rref = mrepo.head.reference.tracking_branch() - if rref is not None: - rcommit = rref.commit - binsha = rcommit.binsha - hexsha = rcommit.hexsha - else: - _logger.error( - "%s a tracking branch was not set for local branch '%s'", - msg_base, - mrepo.head.reference, - ) - # END handle remote ref - else: + upstream = None if checkout_detached else mrepo.active_branch.tracking_branch() + rref = upstream + if ( + git.Head.to_full_path(self.branch_path) == git.Head.to_full_path(".") + and not self.repo.head.is_detached + ): + remote = upstream.remote_name if isinstance(upstream, git.RemoteReference) else "origin" + rref = git.RemoteReference(mrepo, f"refs/remotes/{remote}/{self.repo.active_branch.name}") + # Keep the local branch pointing at its own history when following another branch. + checkout_detached = rref != upstream + + if rref is not None: + rcommit = rref.commit + binsha = rcommit.binsha + hexsha = rcommit.hexsha + elif checkout_detached: _logger.error("%s there was no local tracking branch", msg_base) - # END handle detached head + else: + _logger.error( + "%s a tracking branch was not set for local branch '%s'", msg_base, mrepo.head.reference + ) # END handle to_latest_revision option # Update the working tree. @@ -1169,7 +1176,7 @@ def fetch_remotes(module_repo: "Repo") -> None: else: msg = "Skipping %s on branch '%s' of submodule repo '%s' as it contains un-pushed commits" msg %= ( - is_detached and "checkout" or "reset", + checkout_detached and "checkout" or "reset", mrepo.head, mrepo, ) @@ -1193,7 +1200,7 @@ def fetch_remotes(module_repo: "Repo") -> None: ) if not dry_run and may_reset: - if is_detached: + if checkout_detached: # NOTE: For now we force. The user is not supposed to change # detached submodules anyway. Maybe at some point this becomes # an option, to properly handle user modifications - see below diff --git a/test/test_submodule.py b/test/test_submodule.py index 146dc8b55..3dc41ab5f 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -1961,6 +1961,31 @@ def test_update_to_latest_revision_follows_superproject_branch(self): assert submodule.module().active_branch.name == "dev" assert submodule.module().head.commit == source_repo.heads.dev.commit + @patch_git_config("protocol.file.allow", "always") + def test_update_to_latest_revision_after_superproject_switch(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + with git.Repo(rwdir / "source") as source, git.Repo(rwdir / "clone") as parent: + submodule = parent.submodules[0] + submodule.update(to_latest_revision=True) + with submodule.module() as module: + assert module.active_branch.tracking_branch() == module.remotes.origin.refs.dev + assert module.head.commit == source.heads.dev.commit + + parent.git.checkout("master") + source.index.commit("Advance master again", skip_hooks=True) + submodule.update(to_latest_revision=True) + + with submodule.module() as module: + assert module.head.commit == source.heads.master.commit + assert module.heads.dev.commit == source.heads.dev.commit + + parent.git.checkout("dev") + submodule.update(to_latest_revision=True, no_fetch=True) + + with submodule.module() as module: + assert module.head.commit == source.heads.dev.commit + @patch_git_config("protocol.file.allow", "always") def test_update_to_latest_revision_after_reread_follows_named_branch(self): rwdir = self._fixture("branch-dot", execute=True) From c32759084936e5f1cbc459d1ee1690cd85800b03 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 16:49:22 +0100 Subject: [PATCH 3/5] fix(submodule): honor branch overrides in superproject config When `.gitmodules` sets `branch = .`, Git takes an explicit `submodule..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 --- doc/gix-backend.md | 6 +++++ git/_backend.py | 5 +++- git/objects/submodule/base.py | 46 +++++++++++++++++++++++------------ test/test_config.py | 2 ++ test/test_submodule.py | 22 +++++++++++++++++ 5 files changed, 65 insertions(+), 16 deletions(-) diff --git a/doc/gix-backend.md b/doc/gix-backend.md index cc2ceae4c..03c738d80 100644 --- a/doc/gix-backend.md +++ b/doc/gix-backend.md @@ -1180,6 +1180,12 @@ retain GitPython's configuration contract natively. The scripted `submodule-bytes.sh` regressions cover values, names and cached-field rereads; the native value test prohibits CLI execution. +Repository `config --get` also uses Git for byte keys. Git 2.54.0 can read a raw +key such as `remote.origin-.url`, while GixPython 0.3.0 raises +`UnicodeEncodeError` for its surrogate-escaped form. The scalar lookup in +`test_config_preserves_non_utf8_subsections_and_values` exercises this +fallback, which also applies to submodule branch overrides. + The October 7 inventory identified 951 remote-enumeration reads, 674 actor lookups, 262 remote-property reads, 202 tracking-branch lookups and 111 fetch refspec checks. These are historical call-site counts, not additive savings. diff --git a/git/_backend.py b/git/_backend.py index fce75ac57..bd64e653f 100644 --- a/git/_backend.py +++ b/git/_backend.py @@ -471,7 +471,10 @@ def submodule_config(source: Any) -> Any: def _config(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if len(args) == 2 and args[0] == "--get": snapshot = repo.config_snapshot() - value = snapshot.string(args[1]) + try: + value = snapshot.string(args[1]) + except UnicodeEncodeError as exc: + raise _Unsupported("non-UTF-8 configuration key (GIX-12)") from exc if value is None: if snapshot.boolean(args[1]) is None: raise GitCommandError(["git", "config"], 1) diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 73724aaab..6be2a4361 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -26,6 +26,7 @@ Literal, Mapping, Sequence, + Tuple, Union, cast, ) @@ -901,9 +902,10 @@ def update( the remote will be fetched, and the local tracking branch updated. This only works if we have a local tracking branch, which is the case if the remote repository had a master branch, or if the ``branch`` option was specified - for this submodule and the branch existed remotely. With ``branch = .`` - and an active superproject branch, the submodule follows the remote branch - of the same name and checks it out detached if it differs from the upstream. + for this submodule and the branch existed remotely. A superproject config + override selects the target branch. With ``branch = .`` and an active + superproject branch, the submodule follows the remote branch of the same + name. If the selected branch differs from the upstream, the checkout is detached. :param progress: :class:`UpdateProgress` instance, or ``None`` if no progress should be @@ -981,6 +983,7 @@ def update( mrepo = None freshly_cloned = False + update_branch = None # END init mrepo def fetch_remotes(module_repo: "Repo") -> None: @@ -1099,14 +1102,12 @@ def fetch_remotes(module_repo: "Repo") -> None: if not dry_run: # See whether we have a valid branch to check out. - branch_path = git.Head.to_full_path(self.branch_path) - # gitmodules(5): branch "." names the superproject's current branch. - if branch_path == git.Head.to_full_path(".") and not self.repo.head.is_detached: - branch_path = self.repo.head.reference.path + update_branch = self._branch_for_update() + branch, _ = update_branch try: mrepo = cast("Repo", mrepo) - remote_branch = find_first_remote_branch(mrepo.remotes, git.Head(mrepo, branch_path).name) - local_branch = mkhead(mrepo, branch_path) + remote_branch = find_first_remote_branch(mrepo.remotes, branch.name) + local_branch = mkhead(mrepo, branch.path) local_branch.set_object(remote_branch.commit) mrepo.head.set_reference( local_branch, @@ -1114,7 +1115,7 @@ def fetch_remotes(module_repo: "Repo") -> None: ) mrepo.head.reference.set_tracking_branch(remote_branch) except (IndexError, InvalidGitRepositoryError): - _logger.warning("Failed to checkout tracking branch %s", branch_path) + _logger.warning("Failed to checkout tracking branch %s", branch.path) with self.repo.config_writer() as writer: writer.set_value(sm_section(self.name), "url", self.url) @@ -1135,12 +1136,10 @@ def fetch_remotes(module_repo: "Repo") -> None: msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir upstream = None if checkout_detached else mrepo.active_branch.tracking_branch() rref = upstream - if ( - git.Head.to_full_path(self.branch_path) == git.Head.to_full_path(".") - and not self.repo.head.is_detached - ): + branch, use_configured_branch = update_branch or self._branch_for_update() + if use_configured_branch: remote = upstream.remote_name if isinstance(upstream, git.RemoteReference) else "origin" - rref = git.RemoteReference(mrepo, f"refs/remotes/{remote}/{self.repo.active_branch.name}") + rref = git.RemoteReference(mrepo, f"refs/remotes/{remote}/{branch.name}") # Keep the local branch pointing at its own history when following another branch. checkout_detached = rref != upstream @@ -1826,6 +1825,23 @@ def branch_name(self) -> str: # uses a repository that is available at least (it makes no difference). return git.Head(self.repo, self._branch_path).name + def _branch_for_update(self) -> Tuple["Head", bool]: + """Return the clone branch and whether it selects the latest revision.""" + key = f"submodule.{self.name}.{self.k_head_option}" + try: + override = self.repo.git._call_process_safe("config", "--get", key) + except GitCommandError as exc: + if exc.status != 1: + raise + override = None + + branch = mkhead(self.repo, self.branch_path if override is None else override) + if branch.name != ".": + return branch, override is not None + if not self.repo.head.is_detached: + return self.repo.active_branch, True + return branch, False + @property def url(self) -> str: """:return: The url to the repository our submodule's repository refers to""" diff --git a/test/test_config.py b/test/test_config.py index abf4df5c4..e0164f50c 100644 --- a/test/test_config.py +++ b/test/test_config.py @@ -85,6 +85,8 @@ def test_config_preserves_non_utf8_subsections_and_values(stream): remote = repo.remotes[0] assert remote.name == "origin-\udcff" assert remote.url == "target-\udcfe" + if os.name != "nt": + assert repo.git._call_process_safe("config", "--get", "remote.origin-\udcff.url") == "target-\udcfe" @pytest.mark.skipif(os.name == "nt", reason="Windows command arguments cannot carry arbitrary bytes") diff --git a/test/test_submodule.py b/test/test_submodule.py index 3dc41ab5f..73096e687 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -1986,6 +1986,28 @@ def test_update_to_latest_revision_after_superproject_switch(self): with submodule.module() as module: assert module.head.commit == source.heads.dev.commit + @patch_git_config("protocol.file.allow", "always") + def test_update_to_latest_revision_respects_local_branch_override(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + with git.Repo(rwdir / "source") as source, git.Repo(rwdir / "clone") as parent: + submodule = parent.submodules[0] + parent.git.config("--local", "submodule.module.branch", "master") + submodule.update(to_latest_revision=True) + with submodule.module() as module: + assert module.active_branch.name == "master" + assert module.head.commit == source.heads.master.commit + + parent.git.config("--local", "submodule.module.branch", ".") + submodule.update(to_latest_revision=True, no_fetch=True) + with submodule.module() as module: + assert module.head.commit == source.heads.dev.commit + + parent.git.config("--local", "submodule.module.branch", "master") + submodule.update(to_latest_revision=True, no_fetch=True) + with submodule.module() as module: + assert module.head.commit == source.heads.master.commit + @patch_git_config("protocol.file.allow", "always") def test_update_to_latest_revision_after_reread_follows_named_branch(self): rwdir = self._fixture("branch-dot", execute=True) From 6caf1e1cc5355f6c1992faa27b61f405405fe302 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 16:52:44 +0100 Subject: [PATCH 4/5] fix(submodule): reject inherited latest updates with detached HEAD A latest-revision update with `branch = .` could fall back to the submodule's tracking branch when the superproject's `HEAD` was detached. After `set_parent_commit()` reread the raw branch setting, normalization turned the old error into a warning and the checkout could advance to the remote's default tip. Resolve the effective branch before cloning or fetching. Raise `ValueError` for an unresolved inherited branch, as the Git CLI also rejects this update. Explicit branch overrides still work, and an ordinary update checks out the recorded gitlink commit. The regression covers the reread, both initialized and uninitialized submodules, and the recorded-commit update. Git 2.54.0 rejects the same `submodule update --init --remote` request. All 24 targeted tests passed on each of the CLI and Gix backends. Agent-Model: gpt-6.2-sol Agent-Reasoning-Effort: high --- git/objects/submodule/base.py | 30 +++++++++++++++++++++--------- test/test_submodule.py | 32 ++++++++++++++++++++++++-------- 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 6be2a4361..ebe4c6bb1 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -903,9 +903,9 @@ def update( works if we have a local tracking branch, which is the case if the remote repository had a master branch, or if the ``branch`` option was specified for this submodule and the branch existed remotely. A superproject config - override selects the target branch. With ``branch = .`` and an active - superproject branch, the submodule follows the remote branch of the same - name. If the selected branch differs from the upstream, the checkout is detached. + override selects the target branch. With ``branch = .``, the submodule + follows the remote branch named by the active superproject branch. If + the selected branch differs from the upstream, the checkout is detached. :param progress: :class:`UpdateProgress` instance, or ``None`` if no progress should be @@ -966,6 +966,10 @@ def update( :note: This method is definitely not atomic if `recursive` is ``True``. + :raise ValueError: + If a latest-revision update needs to inherit a branch and the + superproject's HEAD is detached. + :return: self """ @@ -983,7 +987,7 @@ def update( mrepo = None freshly_cloned = False - update_branch = None + latest_branch = None # END init mrepo def fetch_remotes(module_repo: "Repo") -> None: @@ -1026,6 +1030,8 @@ def fetch_remotes(module_repo: "Repo") -> None: ####################################### try: mrepo = self.module() + if to_latest_revision: + latest_branch = self._branch_for_update(to_latest_revision=True) if not no_fetch: fetch_remotes(mrepo) except InvalidGitRepositoryError: @@ -1033,6 +1039,8 @@ def fetch_remotes(module_repo: "Repo") -> None: if not init: return self # END early abort if init is not allowed + if to_latest_revision and latest_branch is None: + latest_branch = self._branch_for_update(to_latest_revision=True) checkout_module_abspath = self.abspath module_abspath = self._module_abspath(self.repo, self.path, self.name) @@ -1102,8 +1110,7 @@ def fetch_remotes(module_repo: "Repo") -> None: if not dry_run: # See whether we have a valid branch to check out. - update_branch = self._branch_for_update() - branch, _ = update_branch + branch, _ = latest_branch or self._branch_for_update() try: mrepo = cast("Repo", mrepo) remote_branch = find_first_remote_branch(mrepo.remotes, branch.name) @@ -1132,11 +1139,11 @@ def fetch_remotes(module_repo: "Repo") -> None: checkout_detached = mrepo.head.is_detached # END handle dry_run - if mrepo is not None and to_latest_revision: + if mrepo is not None and latest_branch is not None: msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir upstream = None if checkout_detached else mrepo.active_branch.tracking_branch() rref = upstream - branch, use_configured_branch = update_branch or self._branch_for_update() + branch, use_configured_branch = latest_branch if use_configured_branch: remote = upstream.remote_name if isinstance(upstream, git.RemoteReference) else "origin" rref = git.RemoteReference(mrepo, f"refs/remotes/{remote}/{branch.name}") @@ -1825,7 +1832,7 @@ def branch_name(self) -> str: # uses a repository that is available at least (it makes no difference). return git.Head(self.repo, self._branch_path).name - def _branch_for_update(self) -> Tuple["Head", bool]: + def _branch_for_update(self, *, to_latest_revision: bool = False) -> Tuple["Head", bool]: """Return the clone branch and whether it selects the latest revision.""" key = f"submodule.{self.name}.{self.k_head_option}" try: @@ -1840,6 +1847,11 @@ def _branch_for_update(self) -> Tuple["Head", bool]: return branch, override is not None if not self.repo.head.is_detached: return self.repo.active_branch, True + if to_latest_revision: + raise ValueError( + f"Cannot update submodule {self.name!r} to the latest revision with branch = . " + "because the superproject HEAD is detached" + ) return branch, False @property diff --git a/test/test_submodule.py b/test/test_submodule.py index 73096e687..b8d6baec8 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -2003,6 +2003,7 @@ def test_update_to_latest_revision_respects_local_branch_override(self): with submodule.module() as module: assert module.head.commit == source.heads.dev.commit + parent.head.set_reference(parent.head.commit) parent.git.config("--local", "submodule.module.branch", "master") submodule.update(to_latest_revision=True, no_fetch=True) with submodule.module() as module: @@ -2026,17 +2027,32 @@ def test_update_to_latest_revision_after_reread_follows_named_branch(self): assert submodule.module().head.commit == source_repo.heads.dev.commit @patch_git_config("protocol.file.allow", "always") - def test_update_branch_dot_with_detached_superproject_warns(self): + def test_update_branch_dot_rejects_latest_revision_with_detached_superproject(self): + # The submodule URL points to this private fixture's source. rwdir = self._fixture("branch-dot", execute=True) - parent_repo = git.Repo(rwdir / "clone") - parent_repo.head.set_reference(parent_repo.head.commit) - submodule = parent_repo.submodules[0] + with git.Repo(rwdir / "source") as source, git.Repo(rwdir / "clone") as parent: + parent.head.set_reference(parent.head.commit) + submodule = parent.submodules[0] + submodule.set_parent_commit(parent.head.commit) + assert submodule.branch_path == "." + remote_tip = source.index.commit("Advance master again", skip_hooks=True) + assert remote_tip.binsha != submodule.binsha - # git refuses here too: there is no superproject branch to follow. - with self.assertLogs("git.objects.submodule.base", "WARNING") as logs: - submodule.update(to_latest_revision=True) + assert submodule.update(init=False, to_latest_revision=True) is submodule + with pytest.raises(ValueError, match="superproject HEAD is detached"): + submodule.update(to_latest_revision=True) + assert not submodule.module_exists() + assert not (Path(parent.git_dir) / "modules" / submodule.name).exists() - assert any("Failed to checkout tracking branch refs/heads/." in line for line in logs.output) + with self.assertLogs("git.objects.submodule.base", "WARNING") as logs: + submodule.update() + assert any("Failed to checkout tracking branch refs/heads/." in line for line in logs.output) + + with mock.patch.object(git.Remote, "fetch", side_effect=AssertionError("Unexpected fetch")): + with pytest.raises(ValueError, match="superproject HEAD is detached"): + submodule.update(init=False, to_latest_revision=True) + with submodule.module() as module: + assert module.head.commit.binsha == submodule.binsha @patch_git_config("protocol.file.allow", "always") def test_update_after_deinit_fetches_new_gitlink_commit(self): From 01abf356779f1a33a2d4f507e2436ff06f90e629 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 16:55:02 +0100 Subject: [PATCH 5/5] fix(submodule): follow symbolic HEAD aliases for branch inheritance When `HEAD` points to `refs/heads/dev` and that ref aliases `refs/heads/master`, `branch = .` selected `origin/dev` through the immediate HEAD target. Git follows the chain and selects `origin/master`. Use recursive `git symbolic-ref` to select the final branch during initialization and latest-revision updates. GixPython 0.3.0's `head_name()` and `head_ref()` stop at the first target, while `follow_to_object()` cannot return an unborn terminal ref. Keep the recursive HEAD lookup on the CLI path and record the gap as GIX-44. The alias regression failed on both backends before the fix. It now matches Git 2.54.0 on initialization and follows a later remote commit. The targeted run passed 25 tests on CLI and 27 on Gix, including two native-only checks. Agent-Model: gpt-6.2-sol Agent-Reasoning-Effort: high --- doc/gix-backend.md | 3 ++- git/_backend.py | 2 ++ git/objects/submodule/base.py | 20 ++++++++++++-------- test/test_submodule.py | 18 ++++++++++++++++++ tests/fixtures/submodule-cases.sh | 6 +++++- 5 files changed, 39 insertions(+), 10 deletions(-) diff --git a/doc/gix-backend.md b/doc/gix-backend.md index 03c738d80..0d43c2224 100644 --- a/doc/gix-backend.md +++ b/doc/gix-backend.md @@ -388,7 +388,7 @@ and predate the current fallback; they do not establish native coverage. | 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 | -| Managed `symbolic_ref` | Nonrecursive target lookup | Mutation, command-level missing-reference diagnostics | +| Managed `symbolic_ref` | Nonrecursive target lookup | Mutation, command-level missing-reference diagnostics, recursive `HEAD` lookup (GIX-44) | | Reference enumeration, `for_each_ref` | Sorted reference names and literal prefixes, preserving symbolic aliases | Dangling symbolic refs, root refs, glob patterns, other formats/options; GIX-25 | | Managed `config --get KEY` | Merged repository config snapshot | Files/streams, enumeration, mutation; GIX-12 | | Submodule enumeration and cached fields | Dedicated native `.gitmodules` parser over the existing worktree/blob source, with raw path/URL/branch values | Non-UTF-8 subsection names, other/duplicate sections, ambiguous brackets, missing/implicit fields and parser errors; GIX-12. Lines other than comments, bare headers and single settings; GIX-35 | @@ -1017,6 +1017,7 @@ identify the historical fixture where needed. | GIX-41 | Bug (open) | With Git 2.54.0 and GixPython 0.4.0, `tree-modes.sh` writes an entry with either an empty mode field or the literal `0`. Both are decoded by `Tree.iter()` as mode zero and kind `commit`. Git rejects the empty field with `malformed mode in tree entry` and lists the literal zero as a gitlink. `test_ambiguous_tree_entry_mode_uses_git` verifies both results for SHA-1 and SHA-256. | Reject a missing mode or expose the distinction between a missing mode and an encoded zero. `_ls_tree()` defers mode zero to Git for validation and formatting. | | GIX-42 | Bug (open) | With Git 2.54.0 and GixPython 0.4.0, `commit.sh negative-date` stores `-1 +0200 1700000000 -0500` in the author, committer and tagger identities. Git's `split_ident_line()` requires unsigned timestamp digits, so `git show --format=%ad --date=raw` reports no date and GitPython's CLI path returns `(0, 0)`. Native signature accessors expose `(-1, +7200)` as seconds and offset east of UTC. | Provide Git-compatible negative timestamp handling. `object_metadata()` retains CLI for negative dates. `test_deserialization_negative_timestamp_matches_git` verifies both object kinds. | | 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-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/git/_backend.py b/git/_backend.py index bd64e653f..19039853f 100644 --- a/git/_backend.py +++ b/git/_backend.py @@ -392,6 +392,8 @@ def reference_info(command: Any, path: str) -> Any: def _symbolic_ref(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: + if args == ["--quiet", "--", "HEAD"]: + raise _Unsupported("recursive HEAD resolution (GIX-44)") if len(args) != 4 or args[:3] != ["--quiet", "--no-recurse", "--"]: raise _Unsupported("reference mutation or options") reference = repo.try_find_reference(safe_encode(args[-1])) diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index ebe4c6bb1..db08e12c1 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -1845,14 +1845,18 @@ def _branch_for_update(self, *, to_latest_revision: bool = False) -> Tuple["Head branch = mkhead(self.repo, self.branch_path if override is None else override) if branch.name != ".": return branch, override is not None - if not self.repo.head.is_detached: - return self.repo.active_branch, True - if to_latest_revision: - raise ValueError( - f"Cannot update submodule {self.name!r} to the latest revision with branch = . " - "because the superproject HEAD is detached" - ) - return branch, False + try: + target = self.repo.git._call_process_safe("symbolic_ref", "--quiet", "--", "HEAD") + except GitCommandError as exc: + if exc.status != 1: + raise + if to_latest_revision: + raise ValueError( + f"Cannot update submodule {self.name!r} to the latest revision with branch = . " + "because the superproject HEAD is detached" + ) from exc + return branch, False + return git.Head(self.repo, target), True @property def url(self) -> str: diff --git a/test/test_submodule.py b/test/test_submodule.py index b8d6baec8..f8dd81aef 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -1961,6 +1961,24 @@ def test_update_to_latest_revision_follows_superproject_branch(self): assert submodule.module().active_branch.name == "dev" assert submodule.module().head.commit == source_repo.heads.dev.commit + @patch_git_config("protocol.file.allow", "always") + def test_update_to_latest_revision_follows_superproject_branch_alias(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot-alias", execute=True) + with git.Repo(rwdir / "source") as source, git.Repo(rwdir / "clone") as parent: + assert parent.git.symbolic_ref("--no-recurse", "HEAD") == "refs/heads/dev" + assert parent.git.symbolic_ref("HEAD") == "refs/heads/master" + submodule = parent.submodules[0] + submodule.update(to_latest_revision=True) + with submodule.module() as module: + assert module.active_branch.name == "master" + assert module.head.commit == source.heads.master.commit + + remote_tip = source.index.commit("Advance master again", skip_hooks=True) + submodule.update(to_latest_revision=True) + with submodule.module() as module: + assert module.head.commit == remote_tip + @patch_git_config("protocol.file.allow", "always") def test_update_to_latest_revision_after_superproject_switch(self): # The submodule URL points to this private fixture's source. diff --git a/tests/fixtures/submodule-cases.sh b/tests/fixtures/submodule-cases.sh index 3a25bc2ec..a2773f65c 100644 --- a/tests/fixtures/submodule-cases.sh +++ b/tests/fixtures/submodule-cases.sh @@ -46,7 +46,7 @@ case "$scenario" in deinit-nonempty) printf '%s' 'user content' > parent/module/file ;; esac ;; - branch-dot) + branch-dot|branch-dot-alias) git init -q -b master source git -C source commit --allow-empty -qm initial git -C source branch dev @@ -60,6 +60,10 @@ case "$scenario" in git -C parent commit -qam 'Track the superproject branch' git -C parent branch dev git clone -q -b dev parent clone + if test "$scenario" = branch-dot-alias; then + git -C clone branch master refs/remotes/origin/master + git -C clone symbolic-ref refs/heads/dev refs/heads/master + fi ;; add-empty) git init -q -b master empty-repo ;; relative)