Skip to content

Commit 91b7274

Browse files
committed
fix(submodule): preserve local branch history during URL changes
A URL-only update tested the recorded gitlink against just the configured branch of the replacement remote. With a local override to divergent `dev`, this could reset a checked-out `master` with unpushed commits even when the replacement still published the recorded gitlink on `master`. Use `git for-each-ref --contains` over the replacement's fetched branches to decide whether a fallback tip is needed. When checking out that tip, detach if another local branch is checked out. Reuse the existing dirty worktree and force checks. Document the ancestry filter's CLI fallback for the Gix backend. Both scripted cases reproduced the branch reset before the fix. The focused URL and offline-update selection passes 15 tests and two subtests under each backend. Ruff and mypy also pass. Agent-Model: unknown
1 parent 5fe2add commit 91b7274

6 files changed

Lines changed: 79 additions & 36 deletions

File tree

‎doc/gix-backend.md‎

Lines changed: 7 additions & 1 deletion
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

‎doc/source/changes.rst‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -207,10 +207,9 @@ API changes
207207
``branch = .``, they return the superproject's current branch, matching
208208
``git submodule update --remote``, and raise ``ValueError`` while the
209209
superproject HEAD is detached. When a submodule's URL changes,
210-
``RootModule.update()`` looks for the submodule's own branch on the new remote,
211-
honouring a ``submodule.<name>.branch`` override in ``.git/config``, rather than
212-
the root module's default branch, which raised ``IndexError`` on remotes
213-
without ``master``.
210+
``RootModule.update()`` keeps the recorded gitlink if a fetched branch contains
211+
it. If it uses the configured branch's remote tip as a fallback, it preserves
212+
a different checked-out local branch by detaching the checkout.
214213
* Commit/tag metadata uses structured Gix decoders when the Gix backend supports
215214
the repository. The CLI backend retains raw decoding because Git has no faithful
216215
formatted query for all commit headers or arbitrary tag objects. ``gpgsig``

‎git/objects/submodule/base.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

‎git/objects/submodule/root.py‎

Lines changed: 22 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import logging
77

88
# typing -------------------------------------------------------------------
9-
from typing import TYPE_CHECKING, Union
9+
from typing import TYPE_CHECKING, Dict, Union
1010

1111
import git
1212
from git.exc import InvalidGitRepositoryError
@@ -167,6 +167,7 @@ def update( # type: ignore[override]
167167

168168
repo = self.repo
169169
sms: "IterableList[Submodule]" = IterableList("name")
170+
fallback_branches: Dict[str, str] = {}
170171

171172
try:
172173
# SETUP BASE COMMIT
@@ -334,35 +335,25 @@ def update( # type: ignore[override]
334335
# Rename the new remote back to what it was.
335336
smr.rename(orig_name)
336337

337-
# Early on, we verified that the our current tracking
338-
# branch exists in the remote. Now we have to ensure
339-
# that the sha we point to is still contained in the new
340-
# remote tracking branch.
341-
if branch.name != ".":
342-
smsha = sm.binsha
343-
found = False
344-
rref = smr.refs[branch.name]
345-
for c in rref.commit.traverse():
346-
if c.binsha == smsha:
347-
found = True
348-
break
349-
# END traverse all commits in search for sha
350-
# END for each commit
351-
352-
if not found:
353-
# Adjust our internal binsha to use the one of the
354-
# remote this way, it will be checked out in the
355-
# next step. This will change the submodule relative
356-
# to us, so the user will be able to commit the
357-
# change easily.
358-
_logger.warning(
359-
"Current sha %s was not contained in the tracking\
360-
branch at the new remote, setting it the the remote's tracking branch",
361-
sm.hexsha,
362-
)
363-
sm.binsha = rref.commit.binsha
364-
# END reset binsha
365-
# END verify resolved tracking branch
338+
# The gitlink can be reachable from any branch on the new remote.
339+
if branch.name != "." and (
340+
not smm.is_valid_object(sm.hexsha, "commit")
341+
or not smm.git._call_process_safe(
342+
"for_each_ref",
343+
"--format=%(refname)",
344+
f"--contains={sm.hexsha}",
345+
"--count=1",
346+
"--",
347+
f"refs/remotes/{orig_name}/",
348+
)
349+
):
350+
_logger.warning(
351+
"Gitlink %s is unavailable on the new remote, using the tip of %s",
352+
sm.hexsha,
353+
branch.name,
354+
)
355+
sm.binsha = smr.refs[branch.name].commit.binsha
356+
fallback_branches[sm.name] = branch.name
366357

367358
# NOTE: All checkout is performed by the base
368359
# implementation of update.
@@ -453,6 +444,7 @@ def update( # type: ignore[override]
453444
force=force_reset,
454445
keep_going=keep_going,
455446
no_fetch=no_fetch,
447+
_fallback_branch=fallback_branches.get(sm.name),
456448
)
457449

458450
# Update recursively depth first - question is which inconsistent state will

‎test/test_submodule.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2204,6 +2204,29 @@ def test_root_update_retries_url_change_after_detached_superproject(self):
22042204
assert Path(module.remotes.origin.url).samefile(rwdir / "moved")
22052205
assert module.head.commit == moved.heads.dev.commit
22062206

2207+
@patch_git_config("protocol.file.allow", "always")
2208+
def test_root_update_url_change_preserves_other_local_branch(self):
2209+
for scenario in ("root-url-local-override", "root-url-local-override-missing-gitlink"):
2210+
with self.subTest(scenario=scenario):
2211+
# The submodule URLs point to this private fixture's source and replacement.
2212+
rwdir = self._fixture(scenario, execute=True)
2213+
with git.Repo(rwdir / "parent") as parent, git.Repo(rwdir / "moved") as moved:
2214+
submodule = parent.submodules[0]
2215+
with submodule.module() as module:
2216+
assert module.active_branch.name == "master"
2217+
unpushed = module.head.commit
2218+
assert unpushed.binsha != submodule.binsha
2219+
2220+
RootModule(parent).update(previous_commit="before-url-change")
2221+
2222+
assert Path(module.remotes.origin.url).samefile(rwdir / "moved")
2223+
assert module.heads.master.commit == unpushed
2224+
if scenario == "root-url-local-override":
2225+
assert module.active_branch == module.heads.master
2226+
else:
2227+
assert module.head.is_detached
2228+
assert module.head.commit == moved.heads.dev.commit
2229+
22072230
@patch_git_config("protocol.file.allow", "always")
22082231
def test_root_update_url_change_checks_submodule_branch(self):
22092232
# The submodule URL points to this private fixture's source.

‎tests/fixtures/submodule-cases.sh‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ case "$scenario" in
4646
deinit-nonempty) printf '%s' 'user content' > parent/module/file ;;
4747
esac
4848
;;
49-
branch-dot|branch-dot-alias|root-url-branch-dot|root-reuse-inherited-branch)
49+
branch-dot|branch-dot-alias|root-url-branch-dot|root-reuse-inherited-branch|root-url-local-override*)
5050
git init -q -b master source
5151
git -C source commit --allow-empty -qm initial
5252
git -C source branch dev
@@ -72,6 +72,22 @@ case "$scenario" in
7272
git -C parent add .gitmodules
7373
git -C parent commit -qm 'Track the superproject branch'
7474
if test "$scenario" = root-reuse-inherited-branch; then exit 0; fi
75+
case "$scenario" in
76+
root-url-local-override*)
77+
git -C parent tag before-url-change
78+
git -C parent/module commit --allow-empty -qm 'Unpushed master commit'
79+
git -C parent config --local submodule.module.branch dev
80+
if test "$scenario" = root-url-local-override-missing-gitlink; then
81+
git clone -q --bare --single-branch -b dev source moved
82+
else
83+
git clone -q --bare source moved
84+
fi
85+
git -C parent config -f .gitmodules submodule.module.url "$root/moved"
86+
git -C parent add .gitmodules
87+
git -C parent commit -qm 'Change submodule URL'
88+
exit 0
89+
;;
90+
esac
7591
git -C parent branch dev
7692
git clone -q -b dev parent clone
7793
if test "$scenario" = branch-dot-alias; then

0 commit comments

Comments
 (0)