diff --git a/doc/gix-backend.md b/doc/gix-backend.md index f2ad15dcb..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 @@ -1017,7 +1023,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..65a8efa6d 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. +* ``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()`` 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 c449b0b2f..04a5ef2ce 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 @@ -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 @@ -1815,10 +1822,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,44 +1840,73 @@ def branch_path(self) -> PathLike: :return: Full repository-relative path as string to the branch we would checkout from the remote and track + + :note: + 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. """ - return self._branch_path + 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" + ) + 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, os.fspath(self.branch_path)).name - 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}" + def _superproject_branch(self) -> Union["Head", None]: + """Return the superproject's current branch, or ``None`` if its HEAD is detached.""" try: - override = self.repo.git._call_process_safe("config", "--get", key) + target = self.repo.git._call_process_safe("symbolic_ref", "--quiet", "--", "HEAD") except GitCommandError as exc: if exc.status != 1: raise - override = None + return None + return git.Head(self.repo, target) - branch = mkhead(self.repo, self.branch_path if override is None else override) - if branch.name != ".": + def _branch_for_update(self, *, to_latest_revision: bool = False) -> Tuple["Head", bool]: + """Return the clone branch and whether it selects the latest revision.""" + 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 os.fspath(branch.path) != "refs/heads/.": 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..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 @@ -304,17 +305,21 @@ 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()): 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. + 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 @@ -330,33 +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. - 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. + # 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( - "Current sha %s was not contained in the tracking\ - branch at the new remote, setting it the the remote's tracking branch", + "Gitlink %s is unavailable on the new remote, using the tip of %s", sm.hexsha, + branch.name, ) - sm.binsha = rref.commit.binsha - # END reset binsha + 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. @@ -372,7 +369,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 +378,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 +390,30 @@ 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 + + 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 progress.update( @@ -442,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 486ef27f9..29a3483cc 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 @@ -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 @@ -2071,6 +2083,176 @@ 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 + + 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. + 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_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. + 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_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. + 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 Path(module.remotes.origin.url).samefile(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) diff --git a/tests/fixtures/submodule-cases.sh b/tests/fixtures/submodule-cases.sh index a2773f65c..8ef3182f3 100644 --- a/tests/fixtures/submodule-cases.sh +++ b/tests/fixtures/submodule-cases.sh @@ -46,24 +46,63 @@ 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|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 - 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 + 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 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)