Skip to content

Commit 1003977

Browse files
authored
Merge pull request #2362 from JROtto5/fix/submodule-branch-dot
fix(submodule): resolve `branch = .` when update() clones a submodule
2 parents 06aa1cd + 01abf35 commit 1003977

6 files changed

Lines changed: 231 additions & 26 deletions

File tree

‎doc/gix-backend.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ and predate the current fallback; they do not establish native coverage.
388388
| 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 |
389389
| Reference object reads | One exact native lookup for direct, symbolic and absent references | Partial names and native decoding errors |
390390
| Reference-name validation | Native full-name validation without opening a repository | Standalone names outside the native grammar; GIX-20 |
391-
| Managed `symbolic_ref` | Nonrecursive target lookup | Mutation, command-level missing-reference diagnostics |
391+
| Managed `symbolic_ref` | Nonrecursive target lookup | Mutation, command-level missing-reference diagnostics, recursive `HEAD` lookup (GIX-44) |
392392
| 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 |
393393
| Managed `config --get KEY` | Merged repository config snapshot | Files/streams, enumeration, mutation; GIX-12 |
394394
| 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.
10171017
| 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. |
10181018
| 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. |
10191019
| 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. |
1020+
| 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. |
10201021

10211022
GIX-14 also covers configured worktree symlink resolution. On macOS with
10221023
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
11801181
`submodule-bytes.sh` regressions cover values, names and cached-field rereads;
11811182
the native value test prohibits CLI execution.
11821183

1184+
Repository `config --get` also uses Git for byte keys. Git 2.54.0 can read a raw
1185+
key such as `remote.origin-<ff>.url`, while GixPython 0.3.0 raises
1186+
`UnicodeEncodeError` for its surrogate-escaped form. The scalar lookup in
1187+
`test_config_preserves_non_utf8_subsections_and_values` exercises this
1188+
fallback, which also applies to submodule branch overrides.
1189+
11831190
The October 7 inventory identified 951 remote-enumeration reads, 674 actor
11841191
lookups, 262 remote-property reads, 202 tracking-branch lookups and 111 fetch
11851192
refspec checks. These are historical call-site counts, not additive savings.

‎git/_backend.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,8 @@ def reference_info(command: Any, path: str) -> Any:
392392

393393

394394
def _symbolic_ref(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes:
395+
if args == ["--quiet", "--", "HEAD"]:
396+
raise _Unsupported("recursive HEAD resolution (GIX-44)")
395397
if len(args) != 4 or args[:3] != ["--quiet", "--no-recurse", "--"]:
396398
raise _Unsupported("reference mutation or options")
397399
reference = repo.try_find_reference(safe_encode(args[-1]))
@@ -471,7 +473,10 @@ def submodule_config(source: Any) -> Any:
471473
def _config(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes:
472474
if len(args) == 2 and args[0] == "--get":
473475
snapshot = repo.config_snapshot()
474-
value = snapshot.string(args[1])
476+
try:
477+
value = snapshot.string(args[1])
478+
except UnicodeEncodeError as exc:
479+
raise _Unsupported("non-UTF-8 configuration key (GIX-12)") from exc
475480
if value is None:
476481
if snapshot.boolean(args[1]) is None:
477482
raise GitCommandError(["git", "config"], 1)

‎git/objects/submodule/base.py‎

Lines changed: 67 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
Literal,
2727
Mapping,
2828
Sequence,
29+
Tuple,
2930
Union,
3031
cast,
3132
)
@@ -901,7 +902,10 @@ def update(
901902
the remote will be fetched, and the local tracking branch updated. This only
902903
works if we have a local tracking branch, which is the case if the remote
903904
repository had a master branch, or if the ``branch`` option was specified
904-
for this submodule and the branch existed remotely.
905+
for this submodule and the branch existed remotely. A superproject config
906+
override selects the target branch. With ``branch = .``, the submodule
907+
follows the remote branch named by the active superproject branch. If
908+
the selected branch differs from the upstream, the checkout is detached.
905909
906910
:param progress:
907911
:class:`UpdateProgress` instance, or ``None`` if no progress should be
@@ -962,6 +966,10 @@ def update(
962966
:note:
963967
This method is definitely not atomic if `recursive` is ``True``.
964968
969+
:raise ValueError:
970+
If a latest-revision update needs to inherit a branch and the
971+
superproject's HEAD is detached.
972+
965973
:return:
966974
self
967975
"""
@@ -979,6 +987,7 @@ def update(
979987

980988
mrepo = None
981989
freshly_cloned = False
990+
latest_branch = None
982991
# END init mrepo
983992

984993
def fetch_remotes(module_repo: "Repo") -> None:
@@ -1021,13 +1030,17 @@ def fetch_remotes(module_repo: "Repo") -> None:
10211030
#######################################
10221031
try:
10231032
mrepo = self.module()
1033+
if to_latest_revision:
1034+
latest_branch = self._branch_for_update(to_latest_revision=True)
10241035
if not no_fetch:
10251036
fetch_remotes(mrepo)
10261037
except InvalidGitRepositoryError:
10271038
mrepo = None
10281039
if not init:
10291040
return self
10301041
# END early abort if init is not allowed
1042+
if to_latest_revision and latest_branch is None:
1043+
latest_branch = self._branch_for_update(to_latest_revision=True)
10311044

10321045
checkout_module_abspath = self.abspath
10331046
module_abspath = self._module_abspath(self.repo, self.path, self.name)
@@ -1097,18 +1110,19 @@ def fetch_remotes(module_repo: "Repo") -> None:
10971110

10981111
if not dry_run:
10991112
# See whether we have a valid branch to check out.
1113+
branch, _ = latest_branch or self._branch_for_update()
11001114
try:
11011115
mrepo = cast("Repo", mrepo)
1102-
remote_branch = find_first_remote_branch(mrepo.remotes, self.branch_name)
1103-
local_branch = mkhead(mrepo, self.branch_path)
1116+
remote_branch = find_first_remote_branch(mrepo.remotes, branch.name)
1117+
local_branch = mkhead(mrepo, branch.path)
11041118
local_branch.set_object(remote_branch.commit)
11051119
mrepo.head.set_reference(
11061120
local_branch,
11071121
logmsg="submodule: attaching head to %s" % local_branch,
11081122
)
11091123
mrepo.head.reference.set_tracking_branch(remote_branch)
11101124
except (IndexError, InvalidGitRepositoryError):
1111-
_logger.warning("Failed to checkout tracking branch %s", self.branch_path)
1125+
_logger.warning("Failed to checkout tracking branch %s", branch.path)
11121126

11131127
with self.repo.config_writer() as writer:
11141128
writer.set_value(sm_section(self.name), "url", self.url)
@@ -1118,31 +1132,34 @@ def fetch_remotes(module_repo: "Repo") -> None:
11181132
#############################
11191133
binsha = self.binsha
11201134
hexsha = self.hexsha
1121-
is_detached = False
1135+
checkout_detached = False
11221136
if mrepo is not None:
11231137
# mrepo is only set if we are not in dry-run mode or if the module
11241138
# existed.
1125-
is_detached = mrepo.head.is_detached
1139+
checkout_detached = mrepo.head.is_detached
11261140
# END handle dry_run
11271141

1128-
if mrepo is not None and to_latest_revision:
1142+
if mrepo is not None and latest_branch is not None:
11291143
msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir
1130-
if not is_detached:
1131-
rref = mrepo.head.reference.tracking_branch()
1132-
if rref is not None:
1133-
rcommit = rref.commit
1134-
binsha = rcommit.binsha
1135-
hexsha = rcommit.hexsha
1136-
else:
1137-
_logger.error(
1138-
"%s a tracking branch was not set for local branch '%s'",
1139-
msg_base,
1140-
mrepo.head.reference,
1141-
)
1142-
# END handle remote ref
1143-
else:
1144+
upstream = None if checkout_detached else mrepo.active_branch.tracking_branch()
1145+
rref = upstream
1146+
branch, use_configured_branch = latest_branch
1147+
if use_configured_branch:
1148+
remote = upstream.remote_name if isinstance(upstream, git.RemoteReference) else "origin"
1149+
rref = git.RemoteReference(mrepo, f"refs/remotes/{remote}/{branch.name}")
1150+
# Keep the local branch pointing at its own history when following another branch.
1151+
checkout_detached = rref != upstream
1152+
1153+
if rref is not None:
1154+
rcommit = rref.commit
1155+
binsha = rcommit.binsha
1156+
hexsha = rcommit.hexsha
1157+
elif checkout_detached:
11441158
_logger.error("%s there was no local tracking branch", msg_base)
1145-
# END handle detached head
1159+
else:
1160+
_logger.error(
1161+
"%s a tracking branch was not set for local branch '%s'", msg_base, mrepo.head.reference
1162+
)
11461163
# END handle to_latest_revision option
11471164

11481165
# Update the working tree.
@@ -1165,7 +1182,7 @@ def fetch_remotes(module_repo: "Repo") -> None:
11651182
else:
11661183
msg = "Skipping %s on branch '%s' of submodule repo '%s' as it contains un-pushed commits"
11671184
msg %= (
1168-
is_detached and "checkout" or "reset",
1185+
checkout_detached and "checkout" or "reset",
11691186
mrepo.head,
11701187
mrepo,
11711188
)
@@ -1189,7 +1206,7 @@ def fetch_remotes(module_repo: "Repo") -> None:
11891206
)
11901207

11911208
if not dry_run and may_reset:
1192-
if is_detached:
1209+
if checkout_detached:
11931210
# NOTE: For now we force. The user is not supposed to change
11941211
# detached submodules anyway. Maybe at some point this becomes
11951212
# an option, to properly handle user modifications - see below
@@ -1815,6 +1832,32 @@ def branch_name(self) -> str:
18151832
# uses a repository that is available at least (it makes no difference).
18161833
return git.Head(self.repo, self._branch_path).name
18171834

1835+
def _branch_for_update(self, *, to_latest_revision: bool = False) -> Tuple["Head", bool]:
1836+
"""Return the clone branch and whether it selects the latest revision."""
1837+
key = f"submodule.{self.name}.{self.k_head_option}"
1838+
try:
1839+
override = self.repo.git._call_process_safe("config", "--get", key)
1840+
except GitCommandError as exc:
1841+
if exc.status != 1:
1842+
raise
1843+
override = None
1844+
1845+
branch = mkhead(self.repo, self.branch_path if override is None else override)
1846+
if branch.name != ".":
1847+
return branch, override is not None
1848+
try:
1849+
target = self.repo.git._call_process_safe("symbolic_ref", "--quiet", "--", "HEAD")
1850+
except GitCommandError as exc:
1851+
if exc.status != 1:
1852+
raise
1853+
if to_latest_revision:
1854+
raise ValueError(
1855+
f"Cannot update submodule {self.name!r} to the latest revision with branch = . "
1856+
"because the superproject HEAD is detached"
1857+
) from exc
1858+
return branch, False
1859+
return git.Head(self.repo, target), True
1860+
18181861
@property
18191862
def url(self) -> str:
18201863
""":return: The url to the repository our submodule's repository refers to"""

‎test/test_config.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ def test_config_preserves_non_utf8_subsections_and_values(stream):
8585
remote = repo.remotes[0]
8686
assert remote.name == "origin-\udcff"
8787
assert remote.url == "target-\udcfe"
88+
if os.name != "nt":
89+
assert repo.git._call_process_safe("config", "--get", "remote.origin-\udcff.url") == "target-\udcfe"
8890

8991

9092
@pytest.mark.skipif(os.name == "nt", reason="Windows command arguments cannot carry arbitrary bytes")

0 commit comments

Comments
 (0)