From 3e0fe160e9e627fa9fc98659daeb288cfa409147 Mon Sep 17 00:00:00 2001 From: JROtto5 <222316562+JROtto5@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:08:46 -0500 Subject: [PATCH 1/8] fix(submodule): resolve `branch = .` in the branch accessors With `submodule..branch = .`, `Submodule.branch_name` returned `.`, `branch_path` returned `refs/heads/.` and `branch` built a head named `.`, none of which Git accepts as a branch, although `update(to_latest_revision=True)` already resolves `.` to the superproject's current branch. The accessors now resolve `.` through `_superproject_branch()`, the `git symbolic-ref --quiet HEAD` lookup `_branch_for_update()` already used, on every call. They follow later superproject branch switches and re-reads after `set_parent_commit()`, and raise `ValueError` when the superproject HEAD is detached, as their docstrings now say. The configured value stays in `_branch_path`; `__repr__` shows it so that `repr()` cannot raise. `RootModule.update()` compares the configured values between revisions, so `dev` to `.` is a change even while both select `dev`. Tracking setup uses `_branch_for_update()`, which keeps the `.git/config` override first. With a detached superproject it logs a warning and leaves the submodule on the recorded commit, as an ordinary update does. On a URL change the commit check now looks in the submodule's branch on the new remote; it used `self.branch_name`, which is the root module's default branch. Four new tests cover branch switches with and without a re-read, detached HEAD for all three accessors, a change from `dev` to `.` in `RootModule.update()` (also on a detached superproject), and a URL change while the submodule tracks `dev` on a new remote without `master`, which raised `IndexError: No item found with id origin/master` before. They fail without this change and pass with it under the `cli` and `gix` backends. `doc/source/changes.rst` notes the new `ValueError` under API changes, and the GIX-44 row in `doc/gix-backend.md` now names `_superproject_branch()` and its callers. Agent-Model: claude-opus-5-5 --- doc/gix-backend.md | 2 +- doc/source/changes.rst | 8 +++ git/objects/submodule/base.py | 59 +++++++++++++++---- git/objects/submodule/root.py | 105 +++++++++++++++++++--------------- test/test_submodule.py | 88 ++++++++++++++++++++++++++++ 5 files changed, 203 insertions(+), 59 deletions(-) diff --git a/doc/gix-backend.md b/doc/gix-backend.md index f2ad15dcb..9f8963bad 100644 --- a/doc/gix-backend.md +++ b/doc/gix-backend.md @@ -1017,7 +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-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._superproject_branch()`, used by `branch`, `branch_name`, `branch_path` and `_branch_for_update()`, uses recursive `git symbolic-ref --quiet -- HEAD` through the CLI fallback. | | GIX-45 | Bug (open) | Git 2.54.0 `submodule update --remote --no-fetch` rejects a bare `branch` key in `.gitmodules` with `missing value for 'submodule.module.branch'`, including before or after `branch = dev`. In GixPython 0.3.0 and 0.4.0, `ModulesFile.from_bytes()` accepts the bare key and `ModulesFile.branch()` returns `None` for an absent or single bare key. `ConfigFile.boolean()` distinguishes these two inputs with `None` and `True`, respectively. When the bare key precedes `branch = dev`, both `ModulesFile.branch().name_bytes()` and `ConfigFile.string()` return `b"dev"`. For an explicit `branch =` with an `origin` remote, Git attempts to resolve `refs/remotes/origin/`, `ModulesFile.branch().name_bytes()` returns `b"HEAD"`, and `ConfigFile.string()` returns `b""`. | Reject valueless branches in a Git-compatible mode or expose all raw values, including implicit ones. `submodule_config()` falls back to the Git config reader for possible bare `branch` keys and uses `ConfigFile.string()` for assigned values. `test_valueless_branch_is_invalid` covers listing and rereads with a single bare key and one followed by an assignment. | GIX-14 also covers configured worktree symlink resolution. On macOS with diff --git a/doc/source/changes.rst b/doc/source/changes.rst index 3f087b8bd..2ed3b5fa8 100644 --- a/doc/source/changes.rst +++ b/doc/source/changes.rst @@ -202,6 +202,14 @@ API changes literally, so an entry named ``*.txt`` no longer removes every ``.txt`` file. Path strings keep their pathspec semantics. ``Submodule.move()`` and ``Submodule.remove()`` remove the submodule's own index entry the same way. +* With ``branch = .``, ``Submodule.branch``, ``branch_name`` and ``branch_path`` + return the superproject's current branch instead of ``.``, matching + ``git submodule update --remote``, and raise ``ValueError`` while the + superproject HEAD is detached. When a submodule's URL changes, + ``RootModule.update()`` looks for the submodule's own branch on the new remote, + honouring a ``submodule..branch`` override in ``.git/config``, rather than + the root module's default branch, which raised ``IndexError`` on remotes + without ``master``. * Commit/tag metadata uses structured Gix decoders when the Gix backend supports the repository. The CLI backend retains raw decoding because Git has no faithful formatted query for all commit headers or arbitrary tag objects. ``gpgsig`` diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index c449b0b2f..97ec35958 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -248,7 +248,7 @@ def __repr__(self) -> str: self._name, self.path, self.url, - self.branch_path, + self._branch_path, ) @classmethod @@ -1815,10 +1815,17 @@ def branch(self) -> "Head": :return: The branch instance that we are to checkout + :note: + A configured branch of ``.`` resolves to the branch with the name of the + superproject's current branch. + :raise git.exc.InvalidGitRepositoryError: If our module is not yet checked out. + + :raise ValueError: + If the configured branch is ``.`` and the superproject HEAD is detached. """ - return mkhead(self.module(), self._branch_path) + return mkhead(self.module(), self.branch_path) @property def branch_path(self) -> PathLike: @@ -1826,18 +1833,49 @@ def branch_path(self) -> PathLike: :return: Full repository-relative path as string to the branch we would checkout from the remote and track + + :note: + A configured branch of ``.`` resolves to the path of the superproject's + current branch. + + :raise ValueError: + If the configured branch is ``.`` and the superproject HEAD is detached. """ - return self._branch_path + if git.Head(self.repo, self._branch_path).name != ".": + return self._branch_path + branch = self._superproject_branch() + if branch is None: + raise ValueError( + f"Cannot resolve branch = . of submodule {self.name!r} because the superproject HEAD is detached" + ) + return branch.path @property def branch_name(self) -> str: """ :return: The name of the branch, which is the shortest possible branch name + + :note: + A configured branch of ``.`` resolves to the name of the superproject's + current branch. + + :raise ValueError: + If the configured branch is ``.`` and the superproject HEAD is detached. """ # Use an instance method, for this we create a temporary Head instance which # uses a repository that is available at least (it makes no difference). - return git.Head(self.repo, self._branch_path).name + return git.Head(self.repo, self.branch_path).name + + def _superproject_branch(self) -> Union["Head", None]: + """Return the superproject's current branch, or ``None`` if its HEAD is detached.""" + try: + target = self.repo.git._call_process_safe("symbolic_ref", "--quiet", "--", "HEAD") + except GitCommandError as exc: + if exc.status != 1: + raise + return None + return git.Head(self.repo, target) def _branch_for_update(self, *, to_latest_revision: bool = False) -> Tuple["Head", bool]: """Return the clone branch and whether it selects the latest revision.""" @@ -1849,21 +1887,18 @@ def _branch_for_update(self, *, to_latest_revision: bool = False) -> Tuple["Head raise override = None - branch = mkhead(self.repo, self.branch_path if override is None else override) + branch = mkhead(self.repo, self._branch_path if override is None else override) if branch.name != ".": return branch, override is not None - try: - target = self.repo.git._call_process_safe("symbolic_ref", "--quiet", "--", "HEAD") - except GitCommandError as exc: - if exc.status != 1: - raise + superproject_branch = self._superproject_branch() + if superproject_branch is None: 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 + return superproject_branch, True @property def url(self) -> str: diff --git a/git/objects/submodule/root.py b/git/objects/submodule/root.py index dbe804c4a..806cbb2f8 100644 --- a/git/objects/submodule/root.py +++ b/git/objects/submodule/root.py @@ -310,11 +310,15 @@ def update( # type: ignore[override] smr.fetch(progress=progress) # If we have a tracking branch, it should be available - # in the new remote as well. - if len([r for r in smr.refs if r.remote_head == sm.branch_name]) == 0: + # in the new remote as well. An inherited branch has no + # name while the superproject HEAD is detached. + branch, _ = sm._branch_for_update(to_latest_revision=to_latest_revision) + if branch.name == ".": + _logger.warning("Failed to resolve tracking branch %s", branch.path) + elif len([r for r in smr.refs if r.remote_head == branch.name]) == 0: raise ValueError( "Submodule branch named %r was not available in new submodule remote at %r" - % (sm.branch_name, sm.url) + % (branch.name, sm.url) ) # END head is not detached @@ -334,29 +338,31 @@ def update( # type: ignore[override] # branch exists in the remote. Now we have to ensure # that the sha we point to is still contained in the new # remote tracking branch. - smsha = sm.binsha - found = False - rref = smr.refs[self.branch_name] - for c in rref.commit.traverse(): - if c.binsha == smsha: - found = True - break - # END traverse all commits in search for sha - # END for each commit - - if not found: - # Adjust our internal binsha to use the one of the - # remote this way, it will be checked out in the - # next step. This will change the submodule relative - # to us, so the user will be able to commit the - # change easily. - _logger.warning( - "Current sha %s was not contained in the tracking\ + if branch.name != ".": + smsha = sm.binsha + found = False + rref = smr.refs[branch.name] + for c in rref.commit.traverse(): + if c.binsha == smsha: + found = True + break + # END traverse all commits in search for sha + # END for each commit + + if not found: + # Adjust our internal binsha to use the one of the + # remote this way, it will be checked out in the + # next step. This will change the submodule relative + # to us, so the user will be able to commit the + # change easily. + _logger.warning( + "Current sha %s was not contained in the tracking\ branch at the new remote, setting it the the remote's tracking branch", - sm.hexsha, - ) - sm.binsha = rref.commit.binsha - # END reset binsha + sm.hexsha, + ) + sm.binsha = rref.commit.binsha + # END reset binsha + # END verify resolved tracking branch # NOTE: All checkout is performed by the base # implementation of update. @@ -372,7 +378,7 @@ def update( # type: ignore[override] # HANDLE PATH CHANGES ##################### - if sm.branch_path != psm.branch_path: + if sm._branch_path != psm._branch_path: # Finally, create a new tracking branch which tracks the new # remote branch. progress.update( @@ -381,7 +387,7 @@ def update( # type: ignore[override] len_csms, prefix + "Changing branch of submodule %r from %s to %s" - % (sm.name, psm.branch_path, sm.branch_path), + % (sm.name, psm._branch_path, sm._branch_path), ) if not dry_run: smm = sm.module() @@ -393,25 +399,32 @@ def update( # type: ignore[override] remote.fetch(progress=progress) # END for each remote - try: - tbr = git.Head.create( - smm, - sm.branch_name, - logmsg="branch: Created from HEAD", - ) - except OSError: - # ...or reuse the existing one. - tbr = git.Head(smm, sm.branch_path) - # END ensure tracking branch exists - - tbr.set_tracking_branch(find_first_remote_branch(smmr, sm.branch_name)) - # NOTE: All head-resetting is done in the base - # implementation of update but we will have to checkout the - # new branch here. As it still points to the currently - # checked out commit, we don't do any harm. - # As we don't want to update working-tree or index, changing - # the ref is all there is to do. - smm.head.reference = tbr + branch, _ = sm._branch_for_update(to_latest_revision=to_latest_revision) + if branch.name == ".": + # An inherited branch has no name while the superproject HEAD + # is detached, which leaves nothing to track. + _logger.warning("Failed to resolve tracking branch %s", branch.path) + else: + try: + tbr = git.Head.create( + smm, + branch.name, + logmsg="branch: Created from HEAD", + ) + except OSError: + # ...or reuse the existing one. + tbr = git.Head(smm, branch.path) + # END ensure tracking branch exists + + tbr.set_tracking_branch(find_first_remote_branch(smmr, branch.name)) + # NOTE: All head-resetting is done in the base + # implementation of update but we will have to checkout the + # new branch here. As it still points to the currently + # checked out commit, we don't do any harm. + # As we don't want to update working-tree or index, changing + # the ref is all there is to do. + smm.head.reference = tbr + # END handle resolved tracking branch # END handle dry_run progress.update( diff --git a/test/test_submodule.py b/test/test_submodule.py index 486ef27f9..9788409ae 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -2071,6 +2071,94 @@ def test_update_branch_dot_rejects_latest_revision_with_detached_superproject(se with submodule.module() as module: assert module.head.commit.binsha == submodule.binsha + @patch_git_config("protocol.file.allow", "always") + def test_branch_dot_accessors_follow_superproject_branch(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + with git.Repo(rwdir / "clone") as parent: + submodule = parent.submodules[0] + submodule.update() + for branch in ("dev", "master"): + parent.git.checkout(branch) + for reread in (False, True): + with self.subTest(branch=branch, reread=reread): + if reread: + submodule.set_parent_commit(parent.head.commit) + assert submodule.branch_name == branch + assert submodule.branch_path == "refs/heads/" + branch + assert submodule.branch.path == "refs/heads/" + branch + + @patch_git_config("protocol.file.allow", "always") + def test_branch_dot_accessors_reject_detached_superproject(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + with git.Repo(rwdir / "clone") as parent: + parent.head.set_reference(parent.head.commit) + submodule = parent.submodules[0] + submodule.update() + for accessor in ("branch", "branch_name", "branch_path"): + with self.subTest(accessor=accessor): + with pytest.raises(ValueError, match="superproject HEAD is detached"): + getattr(submodule, accessor) + assert "branch_path=refs/heads/." in repr(submodule) + with submodule.module() as module: + assert module.head.commit.binsha == submodule.binsha + + @patch_git_config("protocol.file.allow", "always") + def test_root_update_detects_change_to_inherited_branch(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + with git.Repo(rwdir / "clone") as parent: + parent.git.config("-f", ".gitmodules", "submodule.module.branch", "dev") + parent.index.add([".gitmodules"]) + previous = parent.index.commit("Track dev", skip_hooks=True) + parent.git.config("-f", ".gitmodules", "submodule.module.branch", ".") + parent.index.add([".gitmodules"]) + parent.index.commit("Track the superproject branch", skip_hooks=True) + submodule = parent.submodules[0] + submodule.update() + + # Both revisions select dev, yet the configured values differ. + with submodule.module() as module: + module.head.set_reference(module.head.commit) + RootModule(parent).update(previous_commit=previous) + assert module.active_branch.tracking_branch() == module.remotes.origin.refs.dev + assert module.head.commit.binsha == submodule.binsha + + module.head.set_reference(module.head.commit) + parent.head.set_reference(parent.head.commit) + with self.assertLogs("git.objects.submodule.root", "WARNING") as logs: + RootModule(parent).update(previous_commit=previous) + assert any("Failed to resolve tracking branch refs/heads/." in line for line in logs.output) + assert module.head.is_detached + assert module.head.commit.binsha == submodule.binsha + + @patch_git_config("protocol.file.allow", "always") + def test_root_update_url_change_checks_submodule_branch(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + with git.Repo(rwdir / "clone") as parent: + parent.git.config("-f", ".gitmodules", "submodule.module.branch", "dev") + parent.index.add([".gitmodules"]) + previous = parent.index.commit("Track dev", skip_hooks=True) + parent.submodules[0].update() + + # The new remote has no master, the root module's default branch. + moved = rwdir / "moved" + git.Git().clone("-q", "--bare", "--single-branch", "-b", "dev", str(rwdir / "source"), str(moved)) + parent.git.config("-f", ".gitmodules", "submodule.module.url", str(moved)) + parent.index.add([".gitmodules"]) + parent.index.commit("Move the submodule", skip_hooks=True) + submodule = parent.submodules[0] + + # The recorded commit is only on master, so the update moves to dev's tip. + with self.assertLogs("git.objects.submodule.root", "WARNING"): + RootModule(parent).update(previous_commit=previous) + with submodule.module() as module: + assert module.remotes.origin.url == str(moved) + assert module.active_branch.name == "dev" + assert module.head.commit == git.Repo(moved).heads.dev.commit + @patch_git_config("protocol.file.allow", "always") def test_update_after_deinit_fetches_new_gitlink_commit(self): rwdir = self._fixture("deinit-gitlink", execute=True) From 2600a4e89d2fd8b0fb2b380eb90c82e59c8805de Mon Sep 17 00:00:00 2001 From: JROtto5 <222316562+JROtto5@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:35:30 -0500 Subject: [PATCH 2/8] test(submodule): compare the moved URL with `samefile` On Windows the submodule remote URL comes back with forward slashes, so comparing it to `str(moved)` failed on every Windows job. Use `Path(...).samefile(...)` as the other URL checks in this file do. Validated with `test/test_submodule.py` under the `cli` and `gix` backends on Linux; the Windows result comes from CI. Agent-Model: claude-opus-5-5 --- test/test_submodule.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_submodule.py b/test/test_submodule.py index 9788409ae..8f8658979 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -2155,7 +2155,7 @@ def test_root_update_url_change_checks_submodule_branch(self): with self.assertLogs("git.objects.submodule.root", "WARNING"): RootModule(parent).update(previous_commit=previous) with submodule.module() as module: - assert module.remotes.origin.url == str(moved) + assert Path(module.remotes.origin.url).samefile(moved) assert module.active_branch.name == "dev" assert module.head.commit == git.Repo(moved).heads.dev.commit From be93e83e0a7d2d601878addf14d06a0848707344 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:36:33 +0100 Subject: [PATCH 3/8] fix(submodule): preserve path-like branch paths The inheritance check called `Head.name` on the original argument to `Submodule.__init__()`. A full `PurePosixPath` caused both `branch_path` and `branch` to raise because the name lookup uses string methods. Compare the filesystem representation with the inheritance marker and preserve the original named path. Use a string for the shortest-name lookup as well. The new regression failed before the fix. It and the existing branch inheritance accessor tests pass with both the CLI and Gix backends. Agent-Model: unknown --- git/objects/submodule/base.py | 4 ++-- test/test_submodule.py | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 97ec35958..4c6561190 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -1841,7 +1841,7 @@ def branch_path(self) -> PathLike: :raise ValueError: If the configured branch is ``.`` and the superproject HEAD is detached. """ - if git.Head(self.repo, self._branch_path).name != ".": + if os.fspath(self._branch_path) not in (".", "refs/heads/."): return self._branch_path branch = self._superproject_branch() if branch is None: @@ -1865,7 +1865,7 @@ def branch_name(self) -> str: """ # Use an instance method, for this we create a temporary Head instance which # uses a repository that is available at least (it makes no difference). - return git.Head(self.repo, self.branch_path).name + return git.Head(self.repo, os.fspath(self.branch_path)).name def _superproject_branch(self) -> Union["Head", None]: """Return the superproject's current branch, or ``None`` if its HEAD is detached.""" diff --git a/test/test_submodule.py b/test/test_submodule.py index 8f8658979..573100e6e 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -5,7 +5,7 @@ from io import BytesIO import os import os.path as osp -from pathlib import Path +from pathlib import Path, PurePosixPath import shutil import sys from types import SimpleNamespace @@ -2071,6 +2071,23 @@ def test_update_branch_dot_rejects_latest_revision_with_detached_superproject(se with submodule.module() as module: assert module.head.commit.binsha == submodule.binsha + @patch_git_config("protocol.file.allow", "always") + def test_branch_accessors_accept_path_like_branch(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + with git.Repo(rwdir / "clone") as parent: + configured = parent.submodules[0] + configured.update() + branch_path = PurePosixPath("refs/heads/dev") + submodule = Submodule( + parent, configured.binsha, path=configured.path, name=configured.name, branch_path=branch_path + ) + assert submodule.branch_path is branch_path + assert submodule.branch_name == "dev" + branch = submodule.branch + with branch.repo: + assert branch.path == branch_path + @patch_git_config("protocol.file.allow", "always") def test_branch_dot_accessors_follow_superproject_branch(self): # The submodule URL points to this private fixture's source. From 919b1697692f2a5084dfa3f634c1217ed2550794 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:37:19 +0100 Subject: [PATCH 4/8] fix(submodule): honor branch overrides in accessors The accessors resolved `branch = .` from `.gitmodules` even when the superproject's Git config selected a named branch. This exposed the wrong branch on an attached superproject and raised while detached. Use `_branch_for_update()` to apply the same override precedence as remote updates. Preserve the accessor-specific error for unresolved inheritance and the recursive Git lookup for symbolic `HEAD` aliases. Only look up an override when the submodule has a name, so callers can still read an explicit branch path on an unnamed instance. The override and unnamed-path regressions failed before their fixes. The focused branch accessor, override, and alias tests pass under both the CLI and Gix backends. Agent-Model: unknown --- doc/source/changes.rst | 5 +++-- git/objects/submodule/base.py | 27 ++++++++++++++------------- test/test_submodule.py | 16 ++++++++++++++++ 3 files changed, 33 insertions(+), 15 deletions(-) diff --git a/doc/source/changes.rst b/doc/source/changes.rst index 2ed3b5fa8..2f07fcaad 100644 --- a/doc/source/changes.rst +++ b/doc/source/changes.rst @@ -202,8 +202,9 @@ API changes literally, so an entry named ``*.txt`` no longer removes every ``.txt`` file. Path strings keep their pathspec semantics. ``Submodule.move()`` and ``Submodule.remove()`` remove the submodule's own index entry the same way. -* With ``branch = .``, ``Submodule.branch``, ``branch_name`` and ``branch_path`` - return the superproject's current branch instead of ``.``, matching +* ``Submodule.branch``, ``branch_name`` and ``branch_path`` honor a branch + override in the superproject's Git configuration. With an effective + ``branch = .``, they return the superproject's current branch, matching ``git submodule update --remote``, and raise ``ValueError`` while the superproject HEAD is detached. When a submodule's URL changes, ``RootModule.update()`` looks for the submodule's own branch on the new remote, diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 4c6561190..6bcac6aed 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -1835,16 +1835,15 @@ def branch_path(self) -> PathLike: the remote and track :note: - A configured branch of ``.`` resolves to the path of the superproject's + The superproject's Git configuration takes precedence over ``.gitmodules``. + An effective branch of ``.`` resolves to the path of the superproject's current branch. :raise ValueError: If the configured branch is ``.`` and the superproject HEAD is detached. """ - if os.fspath(self._branch_path) not in (".", "refs/heads/."): - return self._branch_path - branch = self._superproject_branch() - if branch is None: + branch, _ = self._branch_for_update() + if os.fspath(branch.path) == "refs/heads/.": raise ValueError( f"Cannot resolve branch = . of submodule {self.name!r} because the superproject HEAD is detached" ) @@ -1879,16 +1878,18 @@ def _superproject_branch(self) -> Union["Head", None]: 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: - override = self.repo.git._call_process_safe("config", "--get", key) - except GitCommandError as exc: - if exc.status != 1: - raise - override = None + name = getattr(self, "name", None) + override = None + if name is not None: + key = f"submodule.{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 branch = mkhead(self.repo, self._branch_path if override is None else override) - if branch.name != ".": + if os.fspath(branch.path) != "refs/heads/.": return branch, override is not None superproject_branch = self._superproject_branch() if superproject_branch is None: diff --git a/test/test_submodule.py b/test/test_submodule.py index 573100e6e..67698c6f2 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -2016,13 +2016,25 @@ def test_update_to_latest_revision_respects_local_branch_override(self): assert module.active_branch.name == "master" assert module.head.commit == source.heads.master.commit + assert submodule.branch_name == "master" + assert submodule.branch_path == "refs/heads/master" + branch = submodule.branch + with branch.repo: + assert branch.name == "master" + parent.git.config("--local", "submodule.module.branch", ".") + assert submodule.branch_name == "dev" submodule.update(to_latest_revision=True, no_fetch=True) 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") + assert submodule.branch_name == "master" + assert submodule.branch_path == "refs/heads/master" + branch = submodule.branch + with branch.repo: + assert branch.name == "master" submodule.update(to_latest_revision=True, no_fetch=True) with submodule.module() as module: assert module.head.commit == source.heads.master.commit @@ -2088,6 +2100,10 @@ def test_branch_accessors_accept_path_like_branch(self): with branch.repo: assert branch.path == branch_path + unnamed = Submodule(parent, configured.binsha, branch_path=branch_path) + assert unnamed.branch_path is branch_path + assert unnamed.branch_name == "dev" + @patch_git_config("protocol.file.allow", "always") def test_branch_dot_accessors_follow_superproject_branch(self): # The submodule URL points to this private fixture's source. From 177a2793030eac6d3c5f3858e66c60b30b452296 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:37:57 +0100 Subject: [PATCH 5/8] fix(submodule): resolve inherited branches before migrating remotes A latest-revision update on a detached superproject could fail after creating `__new_origin__`. A retry saw its matching URL and kept fetching from the original `origin` instead of migrating the remote. Resolve the branch before adding or fetching the temporary remote. The scripted regression verifies that the failed update leaves only the original remote and the retry uses the new remote's newer tip. The regression reproduced the leaked remote before the fix. Six URL change tests pass under both the CLI and Gix backends. Agent-Model: unknown --- git/objects/submodule/root.py | 2 +- test/test_submodule.py | 19 +++++++++++++++++++ tests/fixtures/submodule-cases.sh | 11 ++++++++++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/git/objects/submodule/root.py b/git/objects/submodule/root.py index 806cbb2f8..f3f4a6348 100644 --- a/git/objects/submodule/root.py +++ b/git/objects/submodule/root.py @@ -304,6 +304,7 @@ def update( # type: ignore[override] # offline updates instead of replacing the remote. previous_remote.set_url(git.Git.polish_url(sm_url)) else: + branch, _ = sm._branch_for_update(to_latest_revision=to_latest_revision) assert nn not in [r.name for r in rmts] smr = smm.create_remote(nn, sm_url) with smm.git.custom_environment(**sm._transport_env()): @@ -312,7 +313,6 @@ def update( # type: ignore[override] # If we have a tracking branch, it should be available # in the new remote as well. An inherited branch has no # name while the superproject HEAD is detached. - branch, _ = sm._branch_for_update(to_latest_revision=to_latest_revision) if branch.name == ".": _logger.warning("Failed to resolve tracking branch %s", branch.path) elif len([r for r in smr.refs if r.remote_head == branch.name]) == 0: diff --git a/test/test_submodule.py b/test/test_submodule.py index 67698c6f2..ddd06c64a 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -2166,6 +2166,25 @@ def test_root_update_detects_change_to_inherited_branch(self): assert module.head.is_detached assert module.head.commit.binsha == submodule.binsha + @patch_git_config("protocol.file.allow", "always") + def test_root_update_retries_url_change_after_detached_superproject(self): + # The submodule URLs point to this private fixture's source and replacement. + rwdir = self._fixture("root-url-branch-dot", execute=True) + with git.Repo(rwdir / "clone") as parent, git.Repo(rwdir / "moved") as moved: + root = RootModule(parent) + with parent.submodules[0].module() as module: + with pytest.raises(ValueError, match="superproject HEAD is detached"): + root.update(previous_commit="before-url-change", to_latest_revision=True) + + assert {remote.name for remote in module.remotes} == {"origin"} + assert Path(module.remotes.origin.url).samefile(rwdir / "source") + + parent.git.checkout("dev") + root.update(previous_commit="before-url-change", to_latest_revision=True) + assert {remote.name for remote in module.remotes} == {"origin"} + assert Path(module.remotes.origin.url).samefile(rwdir / "moved") + assert module.head.commit == moved.heads.dev.commit + @patch_git_config("protocol.file.allow", "always") def test_root_update_url_change_checks_submodule_branch(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 a2773f65c..db2ca230c 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-alias) + branch-dot|branch-dot-alias|root-url-branch-dot) git init -q -b master source git -C source commit --allow-empty -qm initial git -C source branch dev @@ -64,6 +64,15 @@ case "$scenario" in git -C clone branch master refs/remotes/origin/master git -C clone symbolic-ref refs/heads/dev refs/heads/master fi + if test "$scenario" = root-url-branch-dot; then + git -C clone submodule update --init + git -C clone tag before-url-change + git clone -q -b dev source moved + git -C moved commit --allow-empty -qm 'Advance dev on the replacement remote' + git -C clone config -f .gitmodules submodule.module.url "$root/moved" + git -C clone commit -qam 'Change submodule URL' + git -C clone checkout -q --detach HEAD + fi ;; add-empty) git init -q -b master empty-repo ;; relative) From 5fe2add9fa6452f883c89ba77e099bea401f54a6 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:39:02 +0100 Subject: [PATCH 6/8] fix(submodule): check out reused branches at a different commit When an inherited branch already pointed to the new gitlink, assigning `HEAD` made the final submodule update skip checkout. The index and working tree still contained the previous branch's files. Perform a `Head.checkout()` when the branch tip differs from the current commit and forward `force_reset`. Keep the lightweight reference switch when both branches point to the same commit. Set up tracking after a successful switch. The scripted fixture has distinct trees and verifies the index and working tree. It failed before the fix. The focused selection passes 25 tests and seven subtests under each backend. Agent-Model: unknown --- git/objects/submodule/root.py | 14 ++++++-------- test/test_submodule.py | 19 +++++++++++++++++++ tests/fixtures/submodule-cases.sh | 22 ++++++++++++++++++---- 3 files changed, 43 insertions(+), 12 deletions(-) diff --git a/git/objects/submodule/root.py b/git/objects/submodule/root.py index f3f4a6348..e646ae3d7 100644 --- a/git/objects/submodule/root.py +++ b/git/objects/submodule/root.py @@ -416,14 +416,12 @@ def update( # type: ignore[override] tbr = git.Head(smm, branch.path) # END ensure tracking branch exists - tbr.set_tracking_branch(find_first_remote_branch(smmr, branch.name)) - # NOTE: All head-resetting is done in the base - # implementation of update but we will have to checkout the - # new branch here. As it still points to the currently - # checked out commit, we don't do any harm. - # As we don't want to update working-tree or index, changing - # the ref is all there is to do. - smm.head.reference = tbr + tracking_branch = find_first_remote_branch(smmr, branch.name) + if tbr.commit == smm.head.commit: + smm.head.reference = tbr + else: + tbr.checkout(force=force_reset) + tbr.set_tracking_branch(tracking_branch) # END handle resolved tracking branch # END handle dry_run diff --git a/test/test_submodule.py b/test/test_submodule.py index ddd06c64a..428ae2c7b 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -2166,6 +2166,25 @@ def test_root_update_detects_change_to_inherited_branch(self): assert module.head.is_detached assert module.head.commit.binsha == submodule.binsha + @patch_git_config("protocol.file.allow", "always") + def test_root_update_checks_out_reused_inherited_branch(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("root-reuse-inherited-branch", execute=True) + with git.Repo(rwdir / "parent") as parent: + submodule = parent.submodules[0] + with submodule.module() as module: + path = Path(submodule.abspath, "file") + assert module.active_branch.name == "master" + assert path.read_text() == "master\n" + assert module.heads.dev.commit.binsha == submodule.binsha + + RootModule(parent).update(previous_commit="before-branch-change") + + assert module.active_branch == module.heads.dev + assert module.head.commit.binsha == submodule.binsha + assert module.git.show(":file") == "dev" + assert path.read_text() == "dev\n" + @patch_git_config("protocol.file.allow", "always") def test_root_update_retries_url_change_after_detached_superproject(self): # The submodule URLs point to this private fixture's source and replacement. diff --git a/tests/fixtures/submodule-cases.sh b/tests/fixtures/submodule-cases.sh index db2ca230c..5403675bf 100644 --- a/tests/fixtures/submodule-cases.sh +++ b/tests/fixtures/submodule-cases.sh @@ -46,18 +46,32 @@ case "$scenario" in deinit-nonempty) printf '%s' 'user content' > parent/module/file ;; esac ;; - branch-dot|branch-dot-alias|root-url-branch-dot) + branch-dot|branch-dot-alias|root-url-branch-dot|root-reuse-inherited-branch) 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' + printf 'master\n' > source/file + git -C source add file + git -C source commit -qm 'Advance master' git -C source checkout -q dev - git -C source commit --allow-empty -qm 'Advance dev' + printf 'dev\n' > source/file + git -C source add file + git -C source commit -qm 'Advance dev' git -C source checkout -q master source="$root/source" add_module module module + if test "$scenario" = root-reuse-inherited-branch; then + git -C parent config -f .gitmodules submodule.module.branch master + git -C parent commit -qam 'Track master' + git -C parent checkout -qb dev + git -C parent/module branch dev origin/dev + git -C parent tag before-branch-change + git -C parent update-index --cacheinfo "160000,$(git -C source rev-parse dev),module" + fi git -C parent config -f .gitmodules submodule.module.branch . - git -C parent commit -qam 'Track the superproject branch' + git -C parent add .gitmodules + git -C parent commit -qm 'Track the superproject branch' + if test "$scenario" = root-reuse-inherited-branch; then exit 0; fi git -C parent branch dev git clone -q -b dev parent clone if test "$scenario" = branch-dot-alias; then From 91b72744184f4121a32beec995867082d8dd1a49 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 05:40:56 +0100 Subject: [PATCH 7/8] fix(submodule): preserve local branch history during URL changes A URL-only update tested the recorded gitlink against just the configured branch of the replacement remote. With a local override to divergent `dev`, this could reset a checked-out `master` with unpushed commits even when the replacement still published the recorded gitlink on `master`. Use `git for-each-ref --contains` over the replacement's fetched branches to decide whether a fallback tip is needed. When checking out that tip, detach if another local branch is checked out. Reuse the existing dirty worktree and force checks. Document the ancestry filter's CLI fallback for the Gix backend. Both scripted cases reproduced the branch reset before the fix. The focused URL and offline-update selection passes 15 tests and two subtests under each backend. Ruff and mypy also pass. Agent-Model: unknown --- doc/gix-backend.md | 8 ++++- doc/source/changes.rst | 7 ++--- git/objects/submodule/base.py | 7 +++++ git/objects/submodule/root.py | 52 +++++++++++++------------------ test/test_submodule.py | 23 ++++++++++++++ tests/fixtures/submodule-cases.sh | 18 ++++++++++- 6 files changed, 79 insertions(+), 36 deletions(-) diff --git a/doc/gix-backend.md b/doc/gix-backend.md index 9f8963bad..3fc7214cd 100644 --- a/doc/gix-backend.md +++ b/doc/gix-backend.md @@ -389,7 +389,7 @@ and predate the current fallback; they do not establish native coverage. | 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, 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 | +| Reference enumeration, `for_each_ref` | Sorted reference names and literal prefixes, preserving symbolic aliases | Dangling symbolic refs, root refs, glob patterns, ancestry filters, 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 native parser errors (GIX-12); possible valueless branch keys (GIX-45) | | Commit hooks | No bound native lookup/execution API | All hooks, including absent hooks; GIX-23 | @@ -414,6 +414,12 @@ and predate the current fallback; they do not establish native coverage. | `Repo.untracked_files` | Native directory walk | Extra status options and non-root command directories | | `Repo.ignored` | Native excludes with tracked-file suppression | Symlink/submodule traversal, unsupported path normalization, and unavailable path metadata | +For a submodule URL change, `RootModule.update()` uses Git's +`for-each-ref --contains` to check whether any fetched branch of the replacement +remote still contains the recorded gitlink. GixPython 0.4.0 exposes reference +enumeration and pairwise merge-base queries. A direct replacement for this CLI +fallback needs a Git-compatible ancestry filter over a ref namespace. + Revision APIs preserve a reference object's validated full name. The shared `Git._check_revision()` first uses the exact reference reader to verify existence and the symbolic-reference chain; it passes the full name rather than the resolved diff --git a/doc/source/changes.rst b/doc/source/changes.rst index 2f07fcaad..65a8efa6d 100644 --- a/doc/source/changes.rst +++ b/doc/source/changes.rst @@ -207,10 +207,9 @@ API changes ``branch = .``, they return the superproject's current branch, matching ``git submodule update --remote``, and raise ``ValueError`` while the superproject HEAD is detached. When a submodule's URL changes, - ``RootModule.update()`` looks for the submodule's own branch on the new remote, - honouring a ``submodule..branch`` override in ``.git/config``, rather than - the root module's default branch, which raised ``IndexError`` on remotes - without ``master``. + ``RootModule.update()`` keeps the recorded gitlink if a fetched branch contains + it. If it uses the configured branch's remote tip as a fallback, it preserves + a different checked-out local branch by detaching the checkout. * Commit/tag metadata uses structured Gix decoders when the Gix backend supports the repository. The CLI backend retains raw decoding because Git has no faithful formatted query for all commit headers or arbitrary tag objects. ``gpgsig`` diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 6bcac6aed..04a5ef2ce 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -894,6 +894,8 @@ def update( allow_unsafe_options: bool = False, allow_unsafe_protocols: bool = False, no_fetch: bool = False, + *, + _fallback_branch: Union[str, None] = None, ) -> "Submodule": """Update the repository of this submodule to point to the checkout we point at with the binsha of this instance. @@ -1161,6 +1163,7 @@ def fetch_remotes(module_repo: "Repo") -> None: rcommit = rref.commit binsha = rcommit.binsha hexsha = rcommit.hexsha + _fallback_branch = None elif checkout_detached: _logger.error("%s there was no local tracking branch", msg_base) else: @@ -1172,6 +1175,10 @@ def fetch_remotes(module_repo: "Repo") -> None: # Update the working tree. # Handles dry_run. if mrepo is not None and (freshly_cloned or mrepo.head.commit.binsha != binsha): + # A URL change can substitute a gitlink from a different branch. + if _fallback_branch is not None and not checkout_detached: + checkout_detached = mrepo.active_branch.name != _fallback_branch + # We must ensure that our destination sha (the one to point to) is in # the future of our current head. Otherwise, we will reset changes that # might have been done on the submodule, but were not yet pushed. We diff --git a/git/objects/submodule/root.py b/git/objects/submodule/root.py index e646ae3d7..b426080ef 100644 --- a/git/objects/submodule/root.py +++ b/git/objects/submodule/root.py @@ -6,7 +6,7 @@ import logging # typing ------------------------------------------------------------------- -from typing import TYPE_CHECKING, Union +from typing import TYPE_CHECKING, Dict, Union import git from git.exc import InvalidGitRepositoryError @@ -167,6 +167,7 @@ def update( # type: ignore[override] repo = self.repo sms: "IterableList[Submodule]" = IterableList("name") + fallback_branches: Dict[str, str] = {} try: # SETUP BASE COMMIT @@ -334,35 +335,25 @@ def update( # type: ignore[override] # Rename the new remote back to what it was. smr.rename(orig_name) - # Early on, we verified that the our current tracking - # branch exists in the remote. Now we have to ensure - # that the sha we point to is still contained in the new - # remote tracking branch. - if branch.name != ".": - smsha = sm.binsha - found = False - rref = smr.refs[branch.name] - for c in rref.commit.traverse(): - if c.binsha == smsha: - found = True - break - # END traverse all commits in search for sha - # END for each commit - - if not found: - # Adjust our internal binsha to use the one of the - # remote this way, it will be checked out in the - # next step. This will change the submodule relative - # to us, so the user will be able to commit the - # change easily. - _logger.warning( - "Current sha %s was not contained in the tracking\ - branch at the new remote, setting it the the remote's tracking branch", - sm.hexsha, - ) - sm.binsha = rref.commit.binsha - # END reset binsha - # END verify resolved tracking branch + # The gitlink can be reachable from any branch on the new remote. + if branch.name != "." and ( + not smm.is_valid_object(sm.hexsha, "commit") + or not smm.git._call_process_safe( + "for_each_ref", + "--format=%(refname)", + f"--contains={sm.hexsha}", + "--count=1", + "--", + f"refs/remotes/{orig_name}/", + ) + ): + _logger.warning( + "Gitlink %s is unavailable on the new remote, using the tip of %s", + sm.hexsha, + branch.name, + ) + sm.binsha = smr.refs[branch.name].commit.binsha + fallback_branches[sm.name] = branch.name # NOTE: All checkout is performed by the base # implementation of update. @@ -453,6 +444,7 @@ def update( # type: ignore[override] force=force_reset, keep_going=keep_going, no_fetch=no_fetch, + _fallback_branch=fallback_branches.get(sm.name), ) # Update recursively depth first - question is which inconsistent state will diff --git a/test/test_submodule.py b/test/test_submodule.py index 428ae2c7b..29a3483cc 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -2204,6 +2204,29 @@ def test_root_update_retries_url_change_after_detached_superproject(self): assert Path(module.remotes.origin.url).samefile(rwdir / "moved") assert module.head.commit == moved.heads.dev.commit + @patch_git_config("protocol.file.allow", "always") + def test_root_update_url_change_preserves_other_local_branch(self): + for scenario in ("root-url-local-override", "root-url-local-override-missing-gitlink"): + with self.subTest(scenario=scenario): + # The submodule URLs point to this private fixture's source and replacement. + rwdir = self._fixture(scenario, execute=True) + with git.Repo(rwdir / "parent") as parent, git.Repo(rwdir / "moved") as moved: + submodule = parent.submodules[0] + with submodule.module() as module: + assert module.active_branch.name == "master" + unpushed = module.head.commit + assert unpushed.binsha != submodule.binsha + + RootModule(parent).update(previous_commit="before-url-change") + + assert Path(module.remotes.origin.url).samefile(rwdir / "moved") + assert module.heads.master.commit == unpushed + if scenario == "root-url-local-override": + assert module.active_branch == module.heads.master + else: + assert module.head.is_detached + assert module.head.commit == moved.heads.dev.commit + @patch_git_config("protocol.file.allow", "always") def test_root_update_url_change_checks_submodule_branch(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 5403675bf..8ef3182f3 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-alias|root-url-branch-dot|root-reuse-inherited-branch) + branch-dot|branch-dot-alias|root-url-branch-dot|root-reuse-inherited-branch|root-url-local-override*) git init -q -b master source git -C source commit --allow-empty -qm initial git -C source branch dev @@ -72,6 +72,22 @@ case "$scenario" in git -C parent add .gitmodules git -C parent commit -qm 'Track the superproject branch' if test "$scenario" = root-reuse-inherited-branch; then exit 0; fi + case "$scenario" in + root-url-local-override*) + git -C parent tag before-url-change + git -C parent/module commit --allow-empty -qm 'Unpushed master commit' + git -C parent config --local submodule.module.branch dev + if test "$scenario" = root-url-local-override-missing-gitlink; then + git clone -q --bare --single-branch -b dev source moved + else + git clone -q --bare source moved + fi + git -C parent config -f .gitmodules submodule.module.url "$root/moved" + git -C parent add .gitmodules + git -C parent commit -qm 'Change submodule URL' + exit 0 + ;; + esac git -C parent branch dev git clone -q -b dev parent clone if test "$scenario" = branch-dot-alias; then From 02febfab076adaed9e48467d416c34bb9ee3668b Mon Sep 17 00:00:00 2001 From: Byron Date: Thu, 26 Nov 2026 08:31:23 +0100 Subject: [PATCH 8/8] review Rubber-stamp, particularly the tests. But investigated Gix shortcomings and will probably fix --contains. Because the submodules API is so unlike Git to begin with, it's hard to tell if the implementation really is desirable. But at least it has *some* defined behaviour now for `.` branches, so maybe it's not worse.