Skip to content
9 changes: 8 additions & 1 deletion doc/gix-backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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-<ff>.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.
Expand Down
7 changes: 6 additions & 1 deletion git/_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]))
Expand Down Expand Up @@ -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)
Expand Down
91 changes: 67 additions & 24 deletions git/objects/submodule/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
Literal,
Mapping,
Sequence,
Tuple,
Union,
cast,
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
"""
Expand All @@ -979,6 +987,7 @@ def update(

mrepo = None
freshly_cloned = False
latest_branch = None
# END init mrepo

def fetch_remotes(module_repo: "Repo") -> None:
Expand Down Expand Up @@ -1021,13 +1030,17 @@ 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:
mrepo = 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)
Expand Down Expand Up @@ -1097,18 +1110,19 @@ 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,
logmsg="submodule: attaching head to %s" % local_branch,
)
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)
Expand All @@ -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.
Expand All @@ -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,
)
Expand All @@ -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
Expand Down Expand Up @@ -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"""
Expand Down
2 changes: 2 additions & 0 deletions test/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading
Loading