Skip to content

Commit 31cb7c8

Browse files
Byroncodex
andcommitted
review
- [P2] Reject valueless submodule branch settings — git/objects/submodule/base.py:1934-1936 When a bare `branch` key replaces `branch = dev`, both backends now interpret it as `refs/heads/master`. The baseline Git rejects the malformed key, but if `origin/master` exists, `Repo.submodule_update(to_latest_revision=True)` can now switch the submodule to `master` and advance it. Use the default only for an absent key and report an explicit valueless key as invalid in both listing and rereads. - [P3] Drop redundant commits from the branch reread test — test/test_submodule.py:2111-2112 The fixture already commits `.gitmodules` and the gitlink, and `set_parent_commit(repo.head.commit)` rereads the working-tree file, not the committed blob. The six add/commit pairs added 96 Git launches in a local CLI run; all six cases still passed without them. Reuse the fixture's committed state and leave the per-case edits unstaged. Assisted-by: GPT 6.2 Sol Co-authored-by: GPT 6.2 Sol <[email protected]>
1 parent 15100e1 commit 31cb7c8

4 files changed

Lines changed: 42 additions & 19 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: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -183,25 +183,34 @@ def _set_cache_(self, attr: str) -> None:
183183
return
184184
# Default submodule values.
185185
try:
186-
self.path = reader.get("path")
186+
path = reader.get("path")
187187
except cp.NoSectionError as e:
188188
if self.repo.working_tree_dir is not None:
189189
raise ValueError(
190190
"This submodule instance does not exist anymore in '%s' file"
191191
% osp.join(self.repo.working_tree_dir, ".gitmodules")
192192
) from e
193+
raise
193194

194-
self._url = reader.get("url")
195-
# GitPython extension values - optional.
196-
# Not get_value(): it turns `branch = 1.10` into the float 1.1.
197-
branch = reader.get(self.k_head_option, fallback=None)
198-
self._branch_path = git.Head.to_full_path(self.k_head_default if branch is None else branch)
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)
199198
elif attr == "_name":
200199
raise AttributeError("Cannot retrieve the name of a submodule if it was not set initially")
201200
else:
202201
super()._set_cache_(attr)
203202
# END handle attribute name
204203

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+
205214
@classmethod
206215
def _get_intermediate_items(cls, item: "Submodule") -> IterableList["Submodule"]:
207216
""":return: All the submodules of our module repository"""
@@ -1974,9 +1983,7 @@ def iter_items(
19741983
if native is NotImplemented:
19751984
p = parser.get(sms, "path")
19761985
u = parser.get(sms, "url")
1977-
b = parser.get(sms, cls.k_head_option, fallback=None)
1978-
if b is None:
1979-
b = cls.k_head_default
1986+
b = cls._configured_branch(n, parser.items_all(sms))
19801987
else:
19811988
p, u = native[n]["path"], native[n]["url"]
19821989
b = native[n].get(cls.k_head_option, cls.k_head_default)

‎test/test_submodule.py‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2229,27 +2229,39 @@ def test_list_only_valid_submodules(self):
22292229
def test_reread_branch_matches_iter_items(self):
22302230
rwdir = self._fixture("module")
22312231
with git.Repo(rwdir / "parent") as repo:
2232-
for branch in ("1.10", "2", "true", "dev", "refs/heads/dev", None):
2232+
parent_commit = repo.head.commit
2233+
for branch in (None, "1.10", "2", "true", "dev", "refs/heads/dev"):
22332234
with self.subTest(branch=branch):
2234-
if branch is None:
2235-
repo.git.config("-f", ".gitmodules", "--unset", "submodule.module.branch")
2236-
with open(rwdir / "parent" / ".gitmodules", "a") as gitmodules:
2237-
gitmodules.write("\tbranch\n")
2238-
else:
2235+
if branch is not None:
22392236
repo.git.config("-f", ".gitmodules", "submodule.module.branch", branch)
2240-
repo.index.add([".gitmodules"])
2241-
repo.index.commit("Track %s" % branch, skip_hooks=True)
22422237
expected = git.Head.to_full_path(Submodule.k_head_default if branch is None else branch)
22432238

22442239
submodule = repo.submodules[0]
22452240
assert submodule.branch_path == expected
22462241
# Both clear the cache, so the branch is read from .gitmodules again.
2247-
submodule.set_parent_commit(repo.head.commit)
2242+
submodule.set_parent_commit(parent_commit)
22482243
assert submodule.branch_path == expected
22492244
assert submodule.branch_name == git.Head(repo, expected).name
22502245
submodule._clear_cache()
22512246
assert submodule.branch_path == expected
22522247

2248+
def test_valueless_branch_is_invalid(self):
2249+
parent = self._fixture("module") / "parent"
2250+
gitmodules = parent / ".gitmodules"
2251+
original = gitmodules.read_bytes()
2252+
with git.Repo(parent) as repo:
2253+
gitmodules.write_bytes(original + b"\tbranch = dev\n")
2254+
submodule = repo.submodules[0]
2255+
assert submodule.branch_path == "refs/heads/dev"
2256+
for trailing_value in (b"", b"\tbranch = dev\n"):
2257+
with self.subTest(trailing_value=trailing_value):
2258+
gitmodules.write_bytes(original + b"\tbranch\n" + trailing_value)
2259+
with pytest.raises(ValueError, match="Submodule 'module' has a valueless branch setting"):
2260+
repo.submodules
2261+
submodule._clear_cache()
2262+
with pytest.raises(ValueError, match="Submodule 'module' has a valueless branch setting"):
2263+
submodule.branch_path
2264+
22532265
@pytest.mark.xfail(
22542266
sys.platform == "win32",
22552267
reason=(

0 commit comments

Comments
 (0)