diff --git a/doc/gix-backend.md b/doc/gix-backend.md index 0d43c2224..f2ad15dcb 100644 --- a/doc/gix-backend.md +++ b/doc/gix-backend.md @@ -391,7 +391,7 @@ and predate the current fallback; they do not establish native coverage. | Managed `symbolic_ref` | Nonrecursive target lookup | Mutation, command-level missing-reference diagnostics, recursive `HEAD` lookup (GIX-44) | | 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 | | Managed `config --get KEY` | Merged repository config snapshot | Files/streams, enumeration, mutation; GIX-12 | -| 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 | +| 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) | | Commit hooks | No bound native lookup/execution API | All hooks, including absent hooks; GIX-23 | | Worktree inventory, `worktree list` | Main and linked worktree metadata, including bare main repositories and locks | Prunable entries; GIX-14 | | `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. | 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. | | 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. | | 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. | +| 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. | GIX-14 also covers configured worktree symlink resolution. On macOS with GixPython 0.3.0, CPython 3.12.14 and Git 2.54.0, set a submodule's diff --git a/git/_backend.py b/git/_backend.py index 19039853f..6f1878ca1 100644 --- a/git/_backend.py +++ b/git/_backend.py @@ -442,6 +442,9 @@ def submodule_config(source: Any) -> Any: # occurrences and duplicate sections until GIX-12 can preserve their order. if b"\0" in data or re.search(rb"\[(?!submodule[ \t])", data, re.I): raise _Unsupported("non-submodule configuration sections (GIX-12)") + # A later assignment can hide an implicit branch from the scalar getters. + if re.search(rb"(?:^|\])[ \t\r\f\v]*branch[ \t\r\f\v]*(?:[#;]|$)", data, re.I | re.M): + raise _Unsupported("possible valueless submodule branch (GIX-45)") modules = gix.ModulesFile.from_bytes(data) with modules.names() as cursor: names = list(cursor) diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index db08e12c1..c449b0b2f 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -179,31 +179,38 @@ def _set_cache_(self, attr: str) -> None: if native is not NotImplemented and self.name in native: values = native[self.name] self.path, self._url = values["path"], values["url"] - self._branch_path = ( - GitConfigParser._string_to_value(values[self.k_head_option]) - if self.k_head_option in values - else git.Head.to_full_path(self.k_head_default) - ) + self._branch_path = git.Head.to_full_path(values.get(self.k_head_option, self.k_head_default)) return # Default submodule values. try: - self.path = reader.get("path") + path = reader.get("path") except cp.NoSectionError as e: if self.repo.working_tree_dir is not None: raise ValueError( "This submodule instance does not exist anymore in '%s' file" % osp.join(self.repo.working_tree_dir, ".gitmodules") ) from e + raise - self._url = reader.get("url") - # GitPython extension values - optional. - self._branch_path = reader.get_value(self.k_head_option, git.Head.to_full_path(self.k_head_default)) + url = reader.get("url") + branch = self._configured_branch(self.name, reader.items_all()) + self.path, self._url, self._branch_path = path, url, git.Head.to_full_path(branch) elif attr == "_name": raise AttributeError("Cannot retrieve the name of a submodule if it was not set initially") else: super()._set_cache_(attr) # END handle attribute name + @classmethod + def _configured_branch(cls, name: str, options: List[Tuple[str, List[Any]]]) -> str: + # Raw values preserve numeric-looking names and valueless keys. + for option, values in options: + if option == cls.k_head_option.lower(): + if None in values: + raise ValueError("Submodule %r has a valueless branch setting" % name) + return values[-1] + return cls.k_head_default + @classmethod def _get_intermediate_items(cls, item: "Submodule") -> IterableList["Submodule"]: """:return: All the submodules of our module repository""" @@ -1976,9 +1983,7 @@ def iter_items( if native is NotImplemented: p = parser.get(sms, "path") u = parser.get(sms, "url") - b = cls.k_head_default - if parser.has_option(sms, cls.k_head_option): - b = str(parser.get(sms, cls.k_head_option)) + b = cls._configured_branch(n, parser.items_all(sms)) else: p, u = native[n]["path"], native[n]["url"] b = native[n].get(cls.k_head_option, cls.k_head_default) diff --git a/test/test_submodule.py b/test/test_submodule.py index f8dd81aef..486ef27f9 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -2052,7 +2052,6 @@ def test_update_branch_dot_rejects_latest_revision_with_detached_superproject(se parent.head.set_reference(parent.head.commit) submodule = parent.submodules[0] submodule.set_parent_commit(parent.head.commit) - assert submodule.branch_path == "." remote_tip = source.index.commit("Advance master again", skip_hooks=True) assert remote_tip.binsha != submodule.binsha @@ -2225,6 +2224,43 @@ def test_list_only_valid_submodules(self): with git.Repo(self._fixture("list-valid", write=False) / "parent") as repo: assert len(repo.submodules) == 0 + @patch_git_config("protocol.file.allow", "always") + def test_reread_branch_matches_iter_items(self): + rwdir = self._fixture("module") + with git.Repo(rwdir / "parent") as repo: + parent_commit = repo.head.commit + for branch in (None, "1.10", "2", "true", "dev", "refs/heads/dev"): + with self.subTest(branch=branch): + if branch is not None: + repo.git.config("-f", ".gitmodules", "submodule.module.branch", branch) + expected = git.Head.to_full_path(Submodule.k_head_default if branch is None else branch) + + submodule = repo.submodules[0] + assert submodule.branch_path == expected + # Both clear the cache, so the branch is read from .gitmodules again. + submodule.set_parent_commit(parent_commit) + assert submodule.branch_path == expected + assert submodule.branch_name == git.Head(repo, expected).name + submodule._clear_cache() + assert submodule.branch_path == expected + + def test_valueless_branch_is_invalid(self): + parent = self._fixture("module") / "parent" + gitmodules = parent / ".gitmodules" + original = gitmodules.read_bytes() + with git.Repo(parent) as repo: + gitmodules.write_bytes(original + b"\tbranch = dev\n") + submodule = repo.submodules[0] + assert submodule.branch_path == "refs/heads/dev" + for trailing_value in (b"", b"\tbranch = dev\n"): + with self.subTest(trailing_value=trailing_value): + gitmodules.write_bytes(original + b"\tbranch\n" + trailing_value) + with pytest.raises(ValueError, match="Submodule 'module' has a valueless branch setting"): + repo.submodules + submodule._clear_cache() + with pytest.raises(ValueError, match="Submodule 'module' has a valueless branch setting"): + submodule.branch_path + @pytest.mark.xfail( sys.platform == "win32", reason=(