Skip to content

Commit 9232dc5

Browse files
authored
Merge pull request #2363 from JROtto5/fix/submodule-branch-reread
fix(submodule): read `branch` as a string when re-reading `.gitmodules`
2 parents 0816ef5 + f0df324 commit 9232dc5

4 files changed

Lines changed: 59 additions & 14 deletions

File tree

‎doc/gix-backend.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ and predate the current fallback; they do not establish native coverage.
391391
| 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 |
394-
| 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 |
394+
| 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 |
396396
| Worktree inventory, `worktree list` | Main and linked worktree metadata, including bare main repositories and locks | Prunable entries; GIX-14 |
397397
| `Repo.merge_base`, `Repo.is_ancestor` | Native graph queries for two revisions | Octopus/fork-point and other options |
@@ -1018,6 +1018,7 @@ identify the historical fixture where needed.
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. |
10201020
| 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. |
1021+
| 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. |
10211022

10221023
GIX-14 also covers configured worktree symlink resolution. On macOS with
10231024
GixPython 0.3.0, CPython 3.12.14 and Git 2.54.0, set a submodule's

‎git/_backend.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,9 @@ def submodule_config(source: Any) -> Any:
442442
# occurrences and duplicate sections until GIX-12 can preserve their order.
443443
if b"\0" in data or re.search(rb"\[(?!submodule[ \t])", data, re.I):
444444
raise _Unsupported("non-submodule configuration sections (GIX-12)")
445+
# A later assignment can hide an implicit branch from the scalar getters.
446+
if re.search(rb"(?:^|\])[ \t\r\f\v]*branch[ \t\r\f\v]*(?:[#;]|$)", data, re.I | re.M):
447+
raise _Unsupported("possible valueless submodule branch (GIX-45)")
445448
modules = gix.ModulesFile.from_bytes(data)
446449
with modules.names() as cursor:
447450
names = list(cursor)

‎git/objects/submodule/base.py‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -179,31 +179,38 @@ def _set_cache_(self, attr: str) -> None:
179179
if native is not NotImplemented and self.name in native:
180180
values = native[self.name]
181181
self.path, self._url = values["path"], values["url"]
182-
self._branch_path = (
183-
GitConfigParser._string_to_value(values[self.k_head_option])
184-
if self.k_head_option in values
185-
else git.Head.to_full_path(self.k_head_default)
186-
)
182+
self._branch_path = git.Head.to_full_path(values.get(self.k_head_option, self.k_head_default))
187183
return
188184
# Default submodule values.
189185
try:
190-
self.path = reader.get("path")
186+
path = reader.get("path")
191187
except cp.NoSectionError as e:
192188
if self.repo.working_tree_dir is not None:
193189
raise ValueError(
194190
"This submodule instance does not exist anymore in '%s' file"
195191
% osp.join(self.repo.working_tree_dir, ".gitmodules")
196192
) from e
193+
raise
197194

198-
self._url = reader.get("url")
199-
# GitPython extension values - optional.
200-
self._branch_path = reader.get_value(self.k_head_option, git.Head.to_full_path(self.k_head_default))
195+
url = reader.get("url")
196+
branch = self._configured_branch(self.name, reader.items_all())
197+
self.path, self._url, self._branch_path = path, url, git.Head.to_full_path(branch)
201198
elif attr == "_name":
202199
raise AttributeError("Cannot retrieve the name of a submodule if it was not set initially")
203200
else:
204201
super()._set_cache_(attr)
205202
# END handle attribute name
206203

204+
@classmethod
205+
def _configured_branch(cls, name: str, options: List[Tuple[str, List[Any]]]) -> str:
206+
# Raw values preserve numeric-looking names and valueless keys.
207+
for option, values in options:
208+
if option == cls.k_head_option.lower():
209+
if None in values:
210+
raise ValueError("Submodule %r has a valueless branch setting" % name)
211+
return values[-1]
212+
return cls.k_head_default
213+
207214
@classmethod
208215
def _get_intermediate_items(cls, item: "Submodule") -> IterableList["Submodule"]:
209216
""":return: All the submodules of our module repository"""
@@ -1976,9 +1983,7 @@ def iter_items(
19761983
if native is NotImplemented:
19771984
p = parser.get(sms, "path")
19781985
u = parser.get(sms, "url")
1979-
b = cls.k_head_default
1980-
if parser.has_option(sms, cls.k_head_option):
1981-
b = str(parser.get(sms, cls.k_head_option))
1986+
b = cls._configured_branch(n, parser.items_all(sms))
19821987
else:
19831988
p, u = native[n]["path"], native[n]["url"]
19841989
b = native[n].get(cls.k_head_option, cls.k_head_default)

‎test/test_submodule.py‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2052,7 +2052,6 @@ def test_update_branch_dot_rejects_latest_revision_with_detached_superproject(se
20522052
parent.head.set_reference(parent.head.commit)
20532053
submodule = parent.submodules[0]
20542054
submodule.set_parent_commit(parent.head.commit)
2055-
assert submodule.branch_path == "."
20562055
remote_tip = source.index.commit("Advance master again", skip_hooks=True)
20572056
assert remote_tip.binsha != submodule.binsha
20582057

@@ -2225,6 +2224,43 @@ def test_list_only_valid_submodules(self):
22252224
with git.Repo(self._fixture("list-valid", write=False) / "parent") as repo:
22262225
assert len(repo.submodules) == 0
22272226

2227+
@patch_git_config("protocol.file.allow", "always")
2228+
def test_reread_branch_matches_iter_items(self):
2229+
rwdir = self._fixture("module")
2230+
with git.Repo(rwdir / "parent") as repo:
2231+
parent_commit = repo.head.commit
2232+
for branch in (None, "1.10", "2", "true", "dev", "refs/heads/dev"):
2233+
with self.subTest(branch=branch):
2234+
if branch is not None:
2235+
repo.git.config("-f", ".gitmodules", "submodule.module.branch", branch)
2236+
expected = git.Head.to_full_path(Submodule.k_head_default if branch is None else branch)
2237+
2238+
submodule = repo.submodules[0]
2239+
assert submodule.branch_path == expected
2240+
# Both clear the cache, so the branch is read from .gitmodules again.
2241+
submodule.set_parent_commit(parent_commit)
2242+
assert submodule.branch_path == expected
2243+
assert submodule.branch_name == git.Head(repo, expected).name
2244+
submodule._clear_cache()
2245+
assert submodule.branch_path == expected
2246+
2247+
def test_valueless_branch_is_invalid(self):
2248+
parent = self._fixture("module") / "parent"
2249+
gitmodules = parent / ".gitmodules"
2250+
original = gitmodules.read_bytes()
2251+
with git.Repo(parent) as repo:
2252+
gitmodules.write_bytes(original + b"\tbranch = dev\n")
2253+
submodule = repo.submodules[0]
2254+
assert submodule.branch_path == "refs/heads/dev"
2255+
for trailing_value in (b"", b"\tbranch = dev\n"):
2256+
with self.subTest(trailing_value=trailing_value):
2257+
gitmodules.write_bytes(original + b"\tbranch\n" + trailing_value)
2258+
with pytest.raises(ValueError, match="Submodule 'module' has a valueless branch setting"):
2259+
repo.submodules
2260+
submodule._clear_cache()
2261+
with pytest.raises(ValueError, match="Submodule 'module' has a valueless branch setting"):
2262+
submodule.branch_path
2263+
22282264
@pytest.mark.xfail(
22292265
sys.platform == "win32",
22302266
reason=(

0 commit comments

Comments
 (0)