diff --git a/doc/gix-backend.md b/doc/gix-backend.md index cc2ceae4c..0d43c2224 100644 --- a/doc/gix-backend.md +++ b/doc/gix-backend.md @@ -388,7 +388,7 @@ and predate the current fallback; they do not establish native coverage. | Tree enumeration, `ls_tree` | Native tree entries with modes, names, and object IDs | Other command options; entries with modes Git canonicalizes or that do not round-trip through native tree encoding; GIX-36 | | Reference object reads | One exact native lookup for direct, symbolic and absent references | Partial names and native decoding errors | | Reference-name validation | Native full-name validation without opening a repository | Standalone names outside the native grammar; GIX-20 | -| Managed `symbolic_ref` | Nonrecursive target lookup | Mutation, command-level missing-reference diagnostics | +| Managed `symbolic_ref` | Nonrecursive target lookup | Mutation, command-level missing-reference diagnostics, recursive `HEAD` lookup (GIX-44) | | Reference enumeration, `for_each_ref` | Sorted reference names and literal prefixes, preserving symbolic aliases | Dangling symbolic refs, root refs, glob patterns, other formats/options; GIX-25 | | Managed `config --get KEY` | Merged repository config snapshot | Files/streams, enumeration, mutation; GIX-12 | | Submodule enumeration and cached fields | Dedicated native `.gitmodules` parser over the existing worktree/blob source, with raw path/URL/branch values | Non-UTF-8 subsection names, other/duplicate sections, ambiguous brackets, missing/implicit fields and parser errors; GIX-12. Lines other than comments, bare headers and single settings; GIX-35 | @@ -1017,6 +1017,7 @@ identify the historical fixture where needed. | GIX-41 | Bug (open) | With Git 2.54.0 and GixPython 0.4.0, `tree-modes.sh` writes an entry with either an empty mode field or the literal `0`. Both are decoded by `Tree.iter()` as mode zero and kind `commit`. Git rejects the empty field with `malformed mode in tree entry` and lists the literal zero as a gitlink. `test_ambiguous_tree_entry_mode_uses_git` verifies both results for SHA-1 and SHA-256. | Reject a missing mode or expose the distinction between a missing mode and an encoded zero. `_ls_tree()` defers mode zero to Git for validation and formatting. | | GIX-42 | Bug (open) | With Git 2.54.0 and GixPython 0.4.0, `commit.sh negative-date` stores `-1 +0200 1700000000 -0500` in the author, committer and tagger identities. Git's `split_ident_line()` requires unsigned timestamp digits, so `git show --format=%ad --date=raw` reports no date and GitPython's CLI path returns `(0, 0)`. Native signature accessors expose `(-1, +7200)` as seconds and offset east of UTC. | Provide Git-compatible negative timestamp handling. `object_metadata()` retains CLI for negative dates. `test_deserialization_negative_timestamp_matches_git` verifies both object kinds. | | GIX-43 | Bug (open) | With Git 2.54.0 and GixPython 0.4.0, `commit.sh spaced-email` stores spaces inside the email brackets ahead of a date with trailing fields. Git's `%ae` and `%ce` preserve these bytes, but native commit author and committer accessors trim them. The native tagger accessor preserves the spaces. | Expose a signature identity that preserves the stored fields with Git-compatible delimiters. `object_metadata()` uses the existing CLI fallback if the native identity fails the raw header comparison. `test_deserialization_preserves_email_whitespace` verifies author, committer and tagger properties. | +| GIX-44 | Bug (open) | With Git 2.54.0 and GixPython 0.3.0, the `branch-dot-alias` case of `submodule-cases.sh` sets `HEAD` to `refs/heads/dev`, which points to `refs/heads/master`. `Repository.head_name()` and `Repository.head_ref().name()` return `refs/heads/dev`. `git symbolic-ref HEAD` returns `refs/heads/master`, and `git submodule update --remote` selects `origin/master` for `branch = .`. `test_update_to_latest_revision_follows_superproject_branch_alias` verifies branch selection on clone and later updates. Redirect `dev` to `refs/heads/missing` and Git returns that terminal name, while `Reference.follow_to_object()` raises a missing-ref error. | Expose the terminal symbolic target with Git-compatible handling of unborn, detached and invalid references. `Submodule._branch_for_update()` uses recursive `git symbolic-ref --quiet -- HEAD` through the CLI fallback. | GIX-14 also covers configured worktree symlink resolution. On macOS with GixPython 0.3.0, CPython 3.12.14 and Git 2.54.0, set a submodule's @@ -1180,6 +1181,12 @@ retain GitPython's configuration contract natively. The scripted `submodule-bytes.sh` regressions cover values, names and cached-field rereads; the native value test prohibits CLI execution. +Repository `config --get` also uses Git for byte keys. Git 2.54.0 can read a raw +key such as `remote.origin-.url`, while GixPython 0.3.0 raises +`UnicodeEncodeError` for its surrogate-escaped form. The scalar lookup in +`test_config_preserves_non_utf8_subsections_and_values` exercises this +fallback, which also applies to submodule branch overrides. + The October 7 inventory identified 951 remote-enumeration reads, 674 actor lookups, 262 remote-property reads, 202 tracking-branch lookups and 111 fetch refspec checks. These are historical call-site counts, not additive savings. diff --git a/git/_backend.py b/git/_backend.py index fce75ac57..19039853f 100644 --- a/git/_backend.py +++ b/git/_backend.py @@ -392,6 +392,8 @@ def reference_info(command: Any, path: str) -> Any: def _symbolic_ref(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: + if args == ["--quiet", "--", "HEAD"]: + raise _Unsupported("recursive HEAD resolution (GIX-44)") if len(args) != 4 or args[:3] != ["--quiet", "--no-recurse", "--"]: raise _Unsupported("reference mutation or options") reference = repo.try_find_reference(safe_encode(args[-1])) @@ -471,7 +473,10 @@ def submodule_config(source: Any) -> Any: def _config(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if len(args) == 2 and args[0] == "--get": snapshot = repo.config_snapshot() - value = snapshot.string(args[1]) + try: + value = snapshot.string(args[1]) + except UnicodeEncodeError as exc: + raise _Unsupported("non-UTF-8 configuration key (GIX-12)") from exc if value is None: if snapshot.boolean(args[1]) is None: raise GitCommandError(["git", "config"], 1) diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 615b9b777..db08e12c1 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -26,6 +26,7 @@ Literal, Mapping, Sequence, + Tuple, Union, cast, ) @@ -901,7 +902,10 @@ def update( the remote will be fetched, and the local tracking branch updated. This only works if we have a local tracking branch, which is the case if the remote repository had a master branch, or if the ``branch`` option was specified - for this submodule and the branch existed remotely. + for this submodule and the branch existed remotely. A superproject config + override selects the target branch. With ``branch = .``, the submodule + follows the remote branch named by the active superproject branch. If + the selected branch differs from the upstream, the checkout is detached. :param progress: :class:`UpdateProgress` instance, or ``None`` if no progress should be @@ -962,6 +966,10 @@ def update( :note: This method is definitely not atomic if `recursive` is ``True``. + :raise ValueError: + If a latest-revision update needs to inherit a branch and the + superproject's HEAD is detached. + :return: self """ @@ -979,6 +987,7 @@ def update( mrepo = None freshly_cloned = False + latest_branch = None # END init mrepo def fetch_remotes(module_repo: "Repo") -> None: @@ -1021,6 +1030,8 @@ def fetch_remotes(module_repo: "Repo") -> None: ####################################### try: mrepo = self.module() + if to_latest_revision: + latest_branch = self._branch_for_update(to_latest_revision=True) if not no_fetch: fetch_remotes(mrepo) except InvalidGitRepositoryError: @@ -1028,6 +1039,8 @@ def fetch_remotes(module_repo: "Repo") -> None: if not init: return self # END early abort if init is not allowed + if to_latest_revision and latest_branch is None: + latest_branch = self._branch_for_update(to_latest_revision=True) checkout_module_abspath = self.abspath module_abspath = self._module_abspath(self.repo, self.path, self.name) @@ -1097,10 +1110,11 @@ def fetch_remotes(module_repo: "Repo") -> None: if not dry_run: # See whether we have a valid branch to check out. + branch, _ = latest_branch or self._branch_for_update() try: mrepo = cast("Repo", mrepo) - remote_branch = find_first_remote_branch(mrepo.remotes, self.branch_name) - local_branch = mkhead(mrepo, self.branch_path) + remote_branch = find_first_remote_branch(mrepo.remotes, branch.name) + local_branch = mkhead(mrepo, branch.path) local_branch.set_object(remote_branch.commit) mrepo.head.set_reference( local_branch, @@ -1108,7 +1122,7 @@ def fetch_remotes(module_repo: "Repo") -> None: ) mrepo.head.reference.set_tracking_branch(remote_branch) except (IndexError, InvalidGitRepositoryError): - _logger.warning("Failed to checkout tracking branch %s", self.branch_path) + _logger.warning("Failed to checkout tracking branch %s", branch.path) with self.repo.config_writer() as writer: writer.set_value(sm_section(self.name), "url", self.url) @@ -1118,31 +1132,34 @@ def fetch_remotes(module_repo: "Repo") -> None: ############################# binsha = self.binsha hexsha = self.hexsha - is_detached = False + checkout_detached = False if mrepo is not None: # mrepo is only set if we are not in dry-run mode or if the module # existed. - is_detached = mrepo.head.is_detached + checkout_detached = mrepo.head.is_detached # END handle dry_run - if mrepo is not None and to_latest_revision: + if mrepo is not None and latest_branch is not None: msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir - if not is_detached: - rref = mrepo.head.reference.tracking_branch() - if rref is not None: - rcommit = rref.commit - binsha = rcommit.binsha - hexsha = rcommit.hexsha - else: - _logger.error( - "%s a tracking branch was not set for local branch '%s'", - msg_base, - mrepo.head.reference, - ) - # END handle remote ref - else: + upstream = None if checkout_detached else mrepo.active_branch.tracking_branch() + rref = upstream + branch, use_configured_branch = latest_branch + if use_configured_branch: + remote = upstream.remote_name if isinstance(upstream, git.RemoteReference) else "origin" + rref = git.RemoteReference(mrepo, f"refs/remotes/{remote}/{branch.name}") + # Keep the local branch pointing at its own history when following another branch. + checkout_detached = rref != upstream + + if rref is not None: + rcommit = rref.commit + binsha = rcommit.binsha + hexsha = rcommit.hexsha + elif checkout_detached: _logger.error("%s there was no local tracking branch", msg_base) - # END handle detached head + else: + _logger.error( + "%s a tracking branch was not set for local branch '%s'", msg_base, mrepo.head.reference + ) # END handle to_latest_revision option # Update the working tree. @@ -1165,7 +1182,7 @@ def fetch_remotes(module_repo: "Repo") -> None: else: msg = "Skipping %s on branch '%s' of submodule repo '%s' as it contains un-pushed commits" msg %= ( - is_detached and "checkout" or "reset", + checkout_detached and "checkout" or "reset", mrepo.head, mrepo, ) @@ -1189,7 +1206,7 @@ def fetch_remotes(module_repo: "Repo") -> None: ) if not dry_run and may_reset: - if is_detached: + if checkout_detached: # NOTE: For now we force. The user is not supposed to change # detached submodules anyway. Maybe at some point this becomes # an option, to properly handle user modifications - see below @@ -1815,6 +1832,32 @@ def branch_name(self) -> str: # uses a repository that is available at least (it makes no difference). return git.Head(self.repo, self._branch_path).name + def _branch_for_update(self, *, 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 + + 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 + if to_latest_revision: + raise ValueError( + f"Cannot update submodule {self.name!r} to the latest revision with branch = . " + "because the superproject HEAD is detached" + ) from exc + return branch, False + return git.Head(self.repo, target), True + @property def url(self) -> str: """:return: The url to the repository our submodule's repository refers to""" diff --git a/test/test_config.py b/test/test_config.py index abf4df5c4..e0164f50c 100644 --- a/test/test_config.py +++ b/test/test_config.py @@ -85,6 +85,8 @@ def test_config_preserves_non_utf8_subsections_and_values(stream): remote = repo.remotes[0] assert remote.name == "origin-\udcff" assert remote.url == "target-\udcfe" + if os.name != "nt": + assert repo.git._call_process_safe("config", "--get", "remote.origin-\udcff.url") == "target-\udcfe" @pytest.mark.skipif(os.name == "nt", reason="Windows command arguments cannot carry arbitrary bytes") diff --git a/test/test_submodule.py b/test/test_submodule.py index f293e8742..f8dd81aef 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -1943,6 +1943,135 @@ def test_update_to_latest_revision_after_deinit_fetches_remote(self): assert submodule.module().head.commit == source_repo.head.commit assert osp.isfile(osp.join(submodule.abspath, "new-file")) + @patch_git_config("protocol.file.allow", "always") + def test_update_to_latest_revision_follows_superproject_branch(self): + for reread in (False, True): + with self.subTest(reread=reread): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + source_repo = git.Repo(rwdir / "source") + parent_repo = git.Repo(rwdir / "clone") + submodule = parent_repo.submodules[0] + if reread: + # Re-reads the branch from .gitmodules as ".", not "refs/heads/.". + submodule.set_parent_commit(parent_repo.head.commit) + + submodule.update(to_latest_revision=True) + + assert submodule.module().active_branch.name == "dev" + assert submodule.module().head.commit == source_repo.heads.dev.commit + + @patch_git_config("protocol.file.allow", "always") + def test_update_to_latest_revision_follows_superproject_branch_alias(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot-alias", execute=True) + with git.Repo(rwdir / "source") as source, git.Repo(rwdir / "clone") as parent: + assert parent.git.symbolic_ref("--no-recurse", "HEAD") == "refs/heads/dev" + assert parent.git.symbolic_ref("HEAD") == "refs/heads/master" + submodule = parent.submodules[0] + submodule.update(to_latest_revision=True) + with submodule.module() as module: + assert module.active_branch.name == "master" + assert module.head.commit == source.heads.master.commit + + remote_tip = source.index.commit("Advance master again", skip_hooks=True) + submodule.update(to_latest_revision=True) + with submodule.module() as module: + assert module.head.commit == remote_tip + + @patch_git_config("protocol.file.allow", "always") + def test_update_to_latest_revision_after_superproject_switch(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + with git.Repo(rwdir / "source") as source, git.Repo(rwdir / "clone") as parent: + submodule = parent.submodules[0] + submodule.update(to_latest_revision=True) + with submodule.module() as module: + assert module.active_branch.tracking_branch() == module.remotes.origin.refs.dev + assert module.head.commit == source.heads.dev.commit + + parent.git.checkout("master") + source.index.commit("Advance master again", skip_hooks=True) + submodule.update(to_latest_revision=True) + + with submodule.module() as module: + assert module.head.commit == source.heads.master.commit + assert module.heads.dev.commit == source.heads.dev.commit + + parent.git.checkout("dev") + submodule.update(to_latest_revision=True, no_fetch=True) + + with submodule.module() as module: + assert module.head.commit == source.heads.dev.commit + + @patch_git_config("protocol.file.allow", "always") + def test_update_to_latest_revision_respects_local_branch_override(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + with git.Repo(rwdir / "source") as source, git.Repo(rwdir / "clone") as parent: + submodule = parent.submodules[0] + parent.git.config("--local", "submodule.module.branch", "master") + submodule.update(to_latest_revision=True) + with submodule.module() as module: + assert module.active_branch.name == "master" + assert module.head.commit == source.heads.master.commit + + parent.git.config("--local", "submodule.module.branch", ".") + submodule.update(to_latest_revision=True, no_fetch=True) + with submodule.module() as module: + assert module.head.commit == source.heads.dev.commit + + parent.head.set_reference(parent.head.commit) + parent.git.config("--local", "submodule.module.branch", "master") + submodule.update(to_latest_revision=True, no_fetch=True) + with submodule.module() as module: + assert module.head.commit == source.heads.master.commit + + @patch_git_config("protocol.file.allow", "always") + def test_update_to_latest_revision_after_reread_follows_named_branch(self): + rwdir = self._fixture("branch-dot", execute=True) + source_repo = git.Repo(rwdir / "source") + parent_repo = git.Repo(rwdir / "clone") + parent_repo.git.config("-f", ".gitmodules", "submodule.module.branch", "dev") + parent_repo.index.add([".gitmodules"]) + parent_repo.index.commit("Track dev", skip_hooks=True) + submodule = parent_repo.submodules[0] + # Re-reads the branch from .gitmodules as "dev", not "refs/heads/dev". + submodule.set_parent_commit(parent_repo.head.commit) + + submodule.update(to_latest_revision=True) + + assert submodule.module().active_branch.name == "dev" + assert submodule.module().head.commit == source_repo.heads.dev.commit + + @patch_git_config("protocol.file.allow", "always") + def test_update_branch_dot_rejects_latest_revision_with_detached_superproject(self): + # The submodule URL points to this private fixture's source. + rwdir = self._fixture("branch-dot", execute=True) + with git.Repo(rwdir / "source") as source, git.Repo(rwdir / "clone") as parent: + parent.head.set_reference(parent.head.commit) + submodule = parent.submodules[0] + submodule.set_parent_commit(parent.head.commit) + assert submodule.branch_path == "." + remote_tip = source.index.commit("Advance master again", skip_hooks=True) + assert remote_tip.binsha != submodule.binsha + + assert submodule.update(init=False, to_latest_revision=True) is submodule + with pytest.raises(ValueError, match="superproject HEAD is detached"): + submodule.update(to_latest_revision=True) + assert not submodule.module_exists() + assert not (Path(parent.git_dir) / "modules" / submodule.name).exists() + + with self.assertLogs("git.objects.submodule.base", "WARNING") as logs: + submodule.update() + assert any("Failed to checkout tracking branch refs/heads/." in line for line in logs.output) + + with mock.patch.object(git.Remote, "fetch", side_effect=AssertionError("Unexpected fetch")): + with pytest.raises(ValueError, match="superproject HEAD is detached"): + submodule.update(init=False, to_latest_revision=True) + with submodule.module() as module: + assert module.head.commit.binsha == submodule.binsha + @patch_git_config("protocol.file.allow", "always") def test_update_after_deinit_fetches_new_gitlink_commit(self): rwdir = self._fixture("deinit-gitlink", execute=True) diff --git a/tests/fixtures/submodule-cases.sh b/tests/fixtures/submodule-cases.sh index 873dafcfa..a2773f65c 100644 --- a/tests/fixtures/submodule-cases.sh +++ b/tests/fixtures/submodule-cases.sh @@ -46,6 +46,25 @@ case "$scenario" in deinit-nonempty) printf '%s' 'user content' > parent/module/file ;; esac ;; + branch-dot|branch-dot-alias) + git init -q -b master source + git -C source commit --allow-empty -qm initial + git -C source branch dev + git -C source commit --allow-empty -qm 'Advance master' + git -C source checkout -q dev + git -C source commit --allow-empty -qm 'Advance dev' + git -C source checkout -q master + source="$root/source" + add_module module module + git -C parent config -f .gitmodules submodule.module.branch . + git -C parent commit -qam 'Track the superproject branch' + git -C parent branch dev + git clone -q -b dev parent clone + if test "$scenario" = branch-dot-alias; then + git -C clone branch master refs/remotes/origin/master + git -C clone symbolic-ref refs/heads/dev refs/heads/master + fi + ;; add-empty) git init -q -b master empty-repo ;; relative) git init -q -b master module