Skip to content

Commit ddc53fc

Browse files
authored
Merge pull request #2365 from JROtto5/fix/submodule-branch-dot-accessors
fix(submodule): resolve `branch = .` in the branch accessors
2 parents 51061f1 + 02febfa commit ddc53fc

6 files changed

Lines changed: 355 additions & 74 deletions

File tree

‎doc/gix-backend.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,7 @@ and predate the current fallback; they do not establish native coverage.
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 |
391391
| Managed `symbolic_ref` | Nonrecursive target lookup | Mutation, command-level missing-reference diagnostics, recursive `HEAD` lookup (GIX-44) |
392-
| 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 |
392+
| 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 |
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 native parser errors (GIX-12); possible valueless branch keys (GIX-45) |
395395
| 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.
414414
| `Repo.untracked_files` | Native directory walk | Extra status options and non-root command directories |
415415
| `Repo.ignored` | Native excludes with tracked-file suppression | Symlink/submodule traversal, unsupported path normalization, and unavailable path metadata |
416416

417+
For a submodule URL change, `RootModule.update()` uses Git's
418+
`for-each-ref --contains` to check whether any fetched branch of the replacement
419+
remote still contains the recorded gitlink. GixPython 0.4.0 exposes reference
420+
enumeration and pairwise merge-base queries. A direct replacement for this CLI
421+
fallback needs a Git-compatible ancestry filter over a ref namespace.
422+
417423
Revision APIs preserve a reference object's validated full name. The shared
418424
`Git._check_revision()` first uses the exact reference reader to verify existence
419425
and the symbolic-reference chain; it passes the full name rather than the resolved
@@ -1017,7 +1023,7 @@ identify the historical fixture where needed.
10171023
| 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. |
10181024
| 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. |
10191025
| 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. |
1026+
| 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. |
10211027
| 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. |
10221028

10231029
GIX-14 also covers configured worktree symlink resolution. On macOS with

‎doc/source/changes.rst‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,14 @@ API changes
203203
literally, so an entry named ``*.txt`` no longer removes every ``.txt`` file.
204204
Path strings keep their pathspec semantics. ``Submodule.move()`` and
205205
``Submodule.remove()`` remove the submodule's own index entry the same way.
206+
* ``Submodule.branch``, ``branch_name`` and ``branch_path`` honor a branch
207+
override in the superproject's Git configuration. With an effective
208+
``branch = .``, they return the superproject's current branch, matching
209+
``git submodule update --remote``, and raise ``ValueError`` while the
210+
superproject HEAD is detached. When a submodule's URL changes,
211+
``RootModule.update()`` keeps the recorded gitlink if a fetched branch contains
212+
it. If it uses the configured branch's remote tip as a fallback, it preserves
213+
a different checked-out local branch by detaching the checkout.
206214
* Commit/tag metadata uses structured Gix decoders when the Gix backend supports
207215
the repository. The CLI backend retains raw decoding because Git has no faithful
208216
formatted query for all commit headers or arbitrary tag objects. ``gpgsig``

‎git/objects/submodule/base.py‎

Lines changed: 61 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ def __repr__(self) -> str:
248248
self._name,
249249
self.path,
250250
self.url,
251-
self.branch_path,
251+
self._branch_path,
252252
)
253253

254254
@classmethod
@@ -894,6 +894,8 @@ def update(
894894
allow_unsafe_options: bool = False,
895895
allow_unsafe_protocols: bool = False,
896896
no_fetch: bool = False,
897+
*,
898+
_fallback_branch: Union[str, None] = None,
897899
) -> "Submodule":
898900
"""Update the repository of this submodule to point to the checkout we point at
899901
with the binsha of this instance.
@@ -1161,6 +1163,7 @@ def fetch_remotes(module_repo: "Repo") -> None:
11611163
rcommit = rref.commit
11621164
binsha = rcommit.binsha
11631165
hexsha = rcommit.hexsha
1166+
_fallback_branch = None
11641167
elif checkout_detached:
11651168
_logger.error("%s there was no local tracking branch", msg_base)
11661169
else:
@@ -1172,6 +1175,10 @@ def fetch_remotes(module_repo: "Repo") -> None:
11721175
# Update the working tree.
11731176
# Handles dry_run.
11741177
if mrepo is not None and (freshly_cloned or mrepo.head.commit.binsha != binsha):
1178+
# A URL change can substitute a gitlink from a different branch.
1179+
if _fallback_branch is not None and not checkout_detached:
1180+
checkout_detached = mrepo.active_branch.name != _fallback_branch
1181+
11751182
# We must ensure that our destination sha (the one to point to) is in
11761183
# the future of our current head. Otherwise, we will reset changes that
11771184
# might have been done on the submodule, but were not yet pushed. We
@@ -1815,55 +1822,91 @@ def branch(self) -> "Head":
18151822
:return:
18161823
The branch instance that we are to checkout
18171824
1825+
:note:
1826+
A configured branch of ``.`` resolves to the branch with the name of the
1827+
superproject's current branch.
1828+
18181829
:raise git.exc.InvalidGitRepositoryError:
18191830
If our module is not yet checked out.
1831+
1832+
:raise ValueError:
1833+
If the configured branch is ``.`` and the superproject HEAD is detached.
18201834
"""
1821-
return mkhead(self.module(), self._branch_path)
1835+
return mkhead(self.module(), self.branch_path)
18221836

18231837
@property
18241838
def branch_path(self) -> PathLike:
18251839
"""
18261840
:return:
18271841
Full repository-relative path as string to the branch we would checkout from
18281842
the remote and track
1843+
1844+
:note:
1845+
The superproject's Git configuration takes precedence over ``.gitmodules``.
1846+
An effective branch of ``.`` resolves to the path of the superproject's
1847+
current branch.
1848+
1849+
:raise ValueError:
1850+
If the configured branch is ``.`` and the superproject HEAD is detached.
18291851
"""
1830-
return self._branch_path
1852+
branch, _ = self._branch_for_update()
1853+
if os.fspath(branch.path) == "refs/heads/.":
1854+
raise ValueError(
1855+
f"Cannot resolve branch = . of submodule {self.name!r} because the superproject HEAD is detached"
1856+
)
1857+
return branch.path
18311858

18321859
@property
18331860
def branch_name(self) -> str:
18341861
"""
18351862
:return:
18361863
The name of the branch, which is the shortest possible branch name
1864+
1865+
:note:
1866+
A configured branch of ``.`` resolves to the name of the superproject's
1867+
current branch.
1868+
1869+
:raise ValueError:
1870+
If the configured branch is ``.`` and the superproject HEAD is detached.
18371871
"""
18381872
# Use an instance method, for this we create a temporary Head instance which
18391873
# uses a repository that is available at least (it makes no difference).
1840-
return git.Head(self.repo, self._branch_path).name
1874+
return git.Head(self.repo, os.fspath(self.branch_path)).name
18411875

1842-
def _branch_for_update(self, *, to_latest_revision: bool = False) -> Tuple["Head", bool]:
1843-
"""Return the clone branch and whether it selects the latest revision."""
1844-
key = f"submodule.{self.name}.{self.k_head_option}"
1876+
def _superproject_branch(self) -> Union["Head", None]:
1877+
"""Return the superproject's current branch, or ``None`` if its HEAD is detached."""
18451878
try:
1846-
override = self.repo.git._call_process_safe("config", "--get", key)
1879+
target = self.repo.git._call_process_safe("symbolic_ref", "--quiet", "--", "HEAD")
18471880
except GitCommandError as exc:
18481881
if exc.status != 1:
18491882
raise
1850-
override = None
1883+
return None
1884+
return git.Head(self.repo, target)
18511885

1852-
branch = mkhead(self.repo, self.branch_path if override is None else override)
1853-
if branch.name != ".":
1886+
def _branch_for_update(self, *, to_latest_revision: bool = False) -> Tuple["Head", bool]:
1887+
"""Return the clone branch and whether it selects the latest revision."""
1888+
name = getattr(self, "name", None)
1889+
override = None
1890+
if name is not None:
1891+
key = f"submodule.{name}.{self.k_head_option}"
1892+
try:
1893+
override = self.repo.git._call_process_safe("config", "--get", key)
1894+
except GitCommandError as exc:
1895+
if exc.status != 1:
1896+
raise
1897+
1898+
branch = mkhead(self.repo, self._branch_path if override is None else override)
1899+
if os.fspath(branch.path) != "refs/heads/.":
18541900
return branch, override is not None
1855-
try:
1856-
target = self.repo.git._call_process_safe("symbolic_ref", "--quiet", "--", "HEAD")
1857-
except GitCommandError as exc:
1858-
if exc.status != 1:
1859-
raise
1901+
superproject_branch = self._superproject_branch()
1902+
if superproject_branch is None:
18601903
if to_latest_revision:
18611904
raise ValueError(
18621905
f"Cannot update submodule {self.name!r} to the latest revision with branch = . "
18631906
"because the superproject HEAD is detached"
1864-
) from exc
1907+
)
18651908
return branch, False
1866-
return git.Head(self.repo, target), True
1909+
return superproject_branch, True
18671910

18681911
@property
18691912
def url(self) -> str:

0 commit comments

Comments
 (0)