Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions doc/gix-backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ and predate the current fallback; they do not establish native coverage.
| Reference object reads | One exact native lookup for direct, symbolic and absent references | Partial names and native decoding errors |
| Reference-name validation | Native full-name validation without opening a repository | Standalone names outside the native grammar; GIX-20 |
| 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 |
| 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 |
| 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 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 |
Expand All @@ -414,6 +414,12 @@ and predate the current fallback; they do not establish native coverage.
| `Repo.untracked_files` | Native directory walk | Extra status options and non-root command directories |
| `Repo.ignored` | Native excludes with tracked-file suppression | Symlink/submodule traversal, unsupported path normalization, and unavailable path metadata |

For a submodule URL change, `RootModule.update()` uses Git's
`for-each-ref --contains` to check whether any fetched branch of the replacement
remote still contains the recorded gitlink. GixPython 0.4.0 exposes reference
enumeration and pairwise merge-base queries. A direct replacement for this CLI
fallback needs a Git-compatible ancestry filter over a ref namespace.

Revision APIs preserve a reference object's validated full name. The shared
`Git._check_revision()` first uses the exact reference reader to verify existence
and the symbolic-reference chain; it passes the full name rather than the resolved
Expand Down Expand Up @@ -1017,7 +1023,7 @@ identify the historical fixture where needed.
| 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. |
| 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-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. |
| 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
Expand Down
8 changes: 8 additions & 0 deletions doc/source/changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,14 @@ API changes
literally, so an entry named ``*.txt`` no longer removes every ``.txt`` file.
Path strings keep their pathspec semantics. ``Submodule.move()`` and
``Submodule.remove()`` remove the submodule's own index entry the same way.
* ``Submodule.branch``, ``branch_name`` and ``branch_path`` honor a branch
override in the superproject's Git configuration. With an effective
``branch = .``, they return the superproject's current branch, matching
``git submodule update --remote``, and raise ``ValueError`` while the
superproject HEAD is detached. When a submodule's URL changes,
``RootModule.update()`` keeps the recorded gitlink if a fetched branch contains
it. If it uses the configured branch's remote tip as a fallback, it preserves
a different checked-out local branch by detaching the checkout.
* Commit/tag metadata uses structured Gix decoders when the Gix backend supports
the repository. The CLI backend retains raw decoding because Git has no faithful
formatted query for all commit headers or arbitrary tag objects. ``gpgsig``
Expand Down
79 changes: 61 additions & 18 deletions git/objects/submodule/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def __repr__(self) -> str:
self._name,
self.path,
self.url,
self.branch_path,
self._branch_path,
)

@classmethod
Expand Down Expand Up @@ -894,6 +894,8 @@ def update(
allow_unsafe_options: bool = False,
allow_unsafe_protocols: bool = False,
no_fetch: bool = False,
*,
_fallback_branch: Union[str, None] = None,
) -> "Submodule":
"""Update the repository of this submodule to point to the checkout we point at
with the binsha of this instance.
Expand Down Expand Up @@ -1161,6 +1163,7 @@ def fetch_remotes(module_repo: "Repo") -> None:
rcommit = rref.commit
binsha = rcommit.binsha
hexsha = rcommit.hexsha
_fallback_branch = None
elif checkout_detached:
_logger.error("%s there was no local tracking branch", msg_base)
else:
Expand All @@ -1172,6 +1175,10 @@ def fetch_remotes(module_repo: "Repo") -> None:
# Update the working tree.
# Handles dry_run.
if mrepo is not None and (freshly_cloned or mrepo.head.commit.binsha != binsha):
# A URL change can substitute a gitlink from a different branch.
if _fallback_branch is not None and not checkout_detached:
checkout_detached = mrepo.active_branch.name != _fallback_branch

# We must ensure that our destination sha (the one to point to) is in
# the future of our current head. Otherwise, we will reset changes that
# might have been done on the submodule, but were not yet pushed. We
Expand Down Expand Up @@ -1815,55 +1822,91 @@ def branch(self) -> "Head":
:return:
The branch instance that we are to checkout

:note:
A configured branch of ``.`` resolves to the branch with the name of the
superproject's current branch.

:raise git.exc.InvalidGitRepositoryError:
If our module is not yet checked out.

:raise ValueError:
If the configured branch is ``.`` and the superproject HEAD is detached.
"""
return mkhead(self.module(), self._branch_path)
return mkhead(self.module(), self.branch_path)

@property
def branch_path(self) -> PathLike:
"""
:return:
Full repository-relative path as string to the branch we would checkout from
the remote and track

:note:
The superproject's Git configuration takes precedence over ``.gitmodules``.
An effective branch of ``.`` resolves to the path of the superproject's
current branch.

:raise ValueError:
If the configured branch is ``.`` and the superproject HEAD is detached.
"""
return self._branch_path
branch, _ = self._branch_for_update()
if os.fspath(branch.path) == "refs/heads/.":
raise ValueError(
f"Cannot resolve branch = . of submodule {self.name!r} because the superproject HEAD is detached"
)
return branch.path

@property
def branch_name(self) -> str:
"""
:return:
The name of the branch, which is the shortest possible branch name

:note:
A configured branch of ``.`` resolves to the name of the superproject's
current branch.

:raise ValueError:
If the configured branch is ``.`` and the superproject HEAD is detached.
"""
# Use an instance method, for this we create a temporary Head instance which
# uses a repository that is available at least (it makes no difference).
return git.Head(self.repo, self._branch_path).name
return git.Head(self.repo, os.fspath(self.branch_path)).name

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

branch = mkhead(self.repo, self.branch_path if override is None else override)
if branch.name != ".":
def _branch_for_update(self, *, to_latest_revision: bool = False) -> Tuple["Head", bool]:
"""Return the clone branch and whether it selects the latest revision."""
name = getattr(self, "name", None)
override = None
if name is not None:
key = f"submodule.{name}.{self.k_head_option}"
try:
override = self.repo.git._call_process_safe("config", "--get", key)
except GitCommandError as exc:
if exc.status != 1:
raise

branch = mkhead(self.repo, self._branch_path if override is None else override)
if os.fspath(branch.path) != "refs/heads/.":
return branch, override is not None
try:
target = self.repo.git._call_process_safe("symbolic_ref", "--quiet", "--", "HEAD")
except GitCommandError as exc:
if exc.status != 1:
raise
superproject_branch = self._superproject_branch()
if superproject_branch is None:
if to_latest_revision:
raise ValueError(
f"Cannot update submodule {self.name!r} to the latest revision with branch = . "
"because the superproject HEAD is detached"
) from exc
)
return branch, False
return git.Head(self.repo, target), True
return superproject_branch, True

@property
def url(self) -> str:
Expand Down
Loading
Loading