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..8f8658979 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 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)