Skip to content

Commit 330fea3

Browse files
committed
fix(git)!: scope one-shot options to the returned wrapper
Rubber-stamp tests. Just a rubber-stamp for everything, but looked at the code at least to see if something sticks out. And what stuck out is statefulness of Git command execution. <!-- agent --> Calling `repo.git(**options)` used to queue options on the shared `Git` wrapper. A source lookup in `Remote.push()` could consume options meant for the push, so the push skipped that lookup and could leave `PushInfo.local_hash` unset. Return a separate wrapper that applies the options to its next subcommand. Chained calls still work, but discarding the wrapper no longer affects later repository operations. Remove the push guard and the commit hook's save-and-restore logic. For repository operations, use per-call environment overrides or `set_persistent_git_options()`. The non-network command, remote, index, and downstream compatibility tests passed on both CLI and Gix (307 passed per backend). Agent-Model: gpt-6.2-sol
1 parent 5088df0 commit 330fea3

7 files changed

Lines changed: 71 additions & 30 deletions

File tree

‎doc/source/changes.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,11 @@ API changes
114114
current repository (``branch.<name>.remote=.``) as the upstream, instead of
115115
constructing an invalid ``refs/remotes/./...`` reference. Git resolves the
116116
upstream location; remote tracking branches retain their existing behavior.
117+
* ``repo.git(**options)`` returns a separate ``Git`` wrapper whose next subcommand
118+
receives the options. Chained calls such as ``repo.git(c="core.abbrev=12").log()``
119+
still work. A standalone ``repo.git(**options)`` call no longer affects later
120+
repository operations; use per-call environment overrides or
121+
``set_persistent_git_options()`` instead.
117122
* ``Remote.push()`` no longer drops results whose source is not a reference,
118123
such as a commit hash or ``HEAD~1``. Their ``PushInfo.local_ref`` is ``None``,
119124
and the new ``PushInfo.local_hash`` holds the hash reported by Git or

‎git/cmd.py‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,10 @@
1919
import sys
2020
import threading
2121
import time
22+
from copy import copy
2223
from subprocess import DEVNULL, PIPE, Popen
2324
from textwrap import dedent
25+
from types import MemberDescriptorType
2426

2527
# typing ---------------------------------------------------------------------------
2628
from typing import (
@@ -43,8 +45,8 @@
4345
overload,
4446
)
4547

46-
from git.compat import defenc, safe_decode, safe_encode
4748
from git import _backend
49+
from git.compat import defenc, safe_decode, safe_encode
4850
from git.exc import (
4951
CommandError,
5052
GitCommandError,
@@ -340,7 +342,13 @@ def dashify(string: str) -> str:
340342

341343

342344
def slots_to_dict(self: "Git", exclude: Sequence[str] = ()) -> Dict[str, Any]:
343-
return {s: getattr(self, s) for s in self.__slots__ if s not in exclude}
345+
state = {}
346+
for cls in reversed(type(self).__mro__):
347+
for name, descriptor in vars(cls).items():
348+
if isinstance(descriptor, MemberDescriptorType) and name not in exclude:
349+
with contextlib.suppress(AttributeError):
350+
state[name] = descriptor.__get__(self)
351+
return state
344352

345353

346354
def dict_to_slots_and__excluded_are_none(self: object, d: Mapping[str, Any], excluded: Sequence[str] = ()) -> None:
@@ -648,7 +656,7 @@ class Git:
648656
]
649657

650658
def __getstate__(self) -> Dict[str, Any]:
651-
return slots_to_dict(self, exclude=self._excluded_)
659+
return {**getattr(self, "__dict__", {}), **slots_to_dict(self, exclude=self._excluded_)}
652660

653661
def __setstate__(self, d: Dict[str, Any]) -> None:
654662
dict_to_slots_and__excluded_are_none(self, d, excluded=self._excluded_)
@@ -1820,7 +1828,10 @@ def _unpack_args(cls, arg_list: Sequence[Any]) -> List[str]:
18201828
return outlist
18211829

18221830
def __call__(self, **kwargs: Any) -> "Git":
1823-
"""Specify command line options to the git executable for a subcommand call.
1831+
"""Return a separate Git wrapper with options for its next subcommand call.
1832+
1833+
The original wrapper is unchanged. Discarding the returned wrapper discards
1834+
the one-shot options as well.
18241835
18251836
:param kwargs:
18261837
A dict of keyword arguments.
@@ -1831,8 +1842,13 @@ def __call__(self, **kwargs: Any) -> "Git":
18311842
18321843
git(work_tree='/tmp').difftool()
18331844
"""
1834-
self._git_options = self.transform_kwargs(split_single_char_options=True, **kwargs)
1835-
return self
1845+
# The copy excludes cached cat-file processes, which must not be shared.
1846+
command = copy(self)
1847+
command._repo = self._repo
1848+
command._environment = self._environment.copy()
1849+
command._repository_environment = self._repository_environment.copy()
1850+
command._git_options = self.transform_kwargs(split_single_char_options=True, **kwargs)
1851+
return command
18361852

18371853
@overload
18381854
def _call_process(

‎git/index/fun.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from git.cmd import Git
99
from git.exc import GitCommandError, HookExecutionError, UnsafeOptionError
1010
from git.types import PathLike
11+
1112
from .typ import BaseIndexEntry
1213

1314
if TYPE_CHECKING:
@@ -38,8 +39,7 @@ def run_commit_hook(name: str, index: "IndexFile", *args: str) -> None:
3839
raise UnsafeOptionError("Git arguments cannot contain NUL bytes")
3940
command = index.repo.git
4041
# Repo's automatic GIT_DIR bypasses Git's discovery-time ownership check.
41-
one_shot_options, command._git_options = command._git_options, ()
42-
options = [*command._persistent_git_options, *one_shot_options]
42+
options = list(command._persistent_git_options)
4343
discovery_env = {}
4444
if (
4545
"GIT_DIR" in command._repository_environment
@@ -57,7 +57,6 @@ def run_commit_hook(name: str, index: "IndexFile", *args: str) -> None:
5757
env=discovery_env,
5858
_repository_redirected="-C" in options,
5959
)
60-
command._git_options = one_shot_options
6160
try:
6261
index.repo.git._call_process_safe(
6362
"hook",

‎git/remote.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ def _from_line(
304304
local_hash = None
305305
if remote.repo.re_hexsha_only.fullmatch(new_sha):
306306
local_hash = new_sha
307-
elif env is not None:
307+
else:
308308
try:
309309
# rev-parse would prefer a ref spelled like the abbreviated ID.
310310
oids = remote.repo.git._call_process_safe(
@@ -1242,9 +1242,8 @@ def push(
12421242
unsafe_options=self.unsafe_git_push_options,
12431243
)
12441244

1245-
# Do not consume Git options reserved for the next command.
1246-
env = None if self.repo.git._git_options else kwargs.get("env") or {}
1247-
sources = self._push_sources(refspec, env) if env is not None else None
1245+
env = kwargs.get("env") or {}
1246+
sources = self._push_sources(refspec, env)
12481247
proc = self.repo.git._call_process_safe(
12491248
"push",
12501249
"--",

‎test/test_git.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,6 +1008,35 @@ def test_single_char_git_options_are_passed_to_git(self):
10081008
output_value = self.git(c="user.name=%s" % input_value).config("--get", "user.name")
10091009
self.assertEqual(input_value, output_value)
10101010

1011+
def test_one_shot_options_belong_to_the_returned_wrapper(self):
1012+
with self.git.custom_environment(GIT_EDITOR="original"):
1013+
configured = self.git(c="core.editor=one-shot")
1014+
configured.update_environment(GIT_EDITOR="configured")
1015+
self.assertEqual(self.git.var("GIT_EDITOR"), "original")
1016+
self.assertEqual(configured.var("GIT_EDITOR"), "configured")
1017+
1018+
configured = self.git(c="gitpython.oneShot=first")
1019+
other = self.git(c="gitpython.oneShot=second")
1020+
with self.assertRaises(GitCommandError):
1021+
self.git.config("--get", "gitpython.oneShot")
1022+
self.assertEqual(configured.config("--get", "gitpython.oneShot"), "first")
1023+
self.assertEqual(other.config("--get", "gitpython.oneShot"), "second")
1024+
with self.assertRaises(GitCommandError):
1025+
configured.config("--get", "gitpython.oneShot")
1026+
1027+
def test_one_shot_options_preserve_subclass_state(self):
1028+
class CustomGit(Git):
1029+
__slots__ = ("label", "__dict__")
1030+
extra: str
1031+
1032+
git = CustomGit(self.git.working_dir)
1033+
git.label = "label"
1034+
git.extra = "extra"
1035+
configured = git(version=True)
1036+
assert isinstance(configured, CustomGit)
1037+
self.assertEqual((configured.label, configured.extra), ("label", "extra"))
1038+
self.assertEqual(configured.NoOp(), git.version())
1039+
10111040
def test_change_to_transform_kwargs_does_not_break_command_options(self):
10121041
self.git.log(n=1)
10131042

‎test/test_index.py‎

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
import pytest
2020

2121
from git import NULL_TREE, BlobFilter, Diff, Git, IndexFile, Object, Repo, Tree
22-
from git.diff import NULL_TREE_SHA
2322
from git.compat import defenc
23+
from git.diff import NULL_TREE_SHA
2424
from git.exc import (
2525
CheckoutError,
2626
GitCommandError,
@@ -35,8 +35,8 @@
3535
from git.objects import Blob
3636
from git.util import Actor, cwd, hex_to_bin, rmtree
3737
from test.lib import PathLikeMock, TestBase, fixture, fixture_path, with_rw_directory, with_rw_repo
38-
from test.lib.helper import symlinks_supported, xfail_if_raises
3938
from test.lib.fixtures import ROOT, fixture_repo, writable_fixture
39+
from test.lib.helper import symlinks_supported, xfail_if_raises
4040

4141
_logger = logging.getLogger(__name__)
4242

@@ -1286,7 +1286,7 @@ def test_pre_commit_hook_not_run_in_repository_git_refuses(self):
12861286
output.unlink()
12871287

12881288
def test_commit_hook_preserves_explicit_repository_selection(self):
1289-
for selection in ("one-shot", "persistent", "environment", "git-dir-option"):
1289+
for selection in ("persistent", "environment", "git-dir-option"):
12901290
with self.subTest(selection=selection), fixture_repo("hook-ownership.sh", "regular", write=True) as repo:
12911291
with Repo(repo.git_dir) as metadata:
12921292
index = metadata.index
@@ -1295,26 +1295,18 @@ def test_commit_hook_preserves_explicit_repository_selection(self):
12951295
environment = {"GIT_DIR": ".git"} if selection == "environment" else {}
12961296
with baseline.custom_environment(**environment), metadata.git.custom_environment(**environment):
12971297
for command in (baseline, metadata.git):
1298-
if selection == "one-shot":
1299-
command(C=".git")
1300-
elif selection == "persistent":
1298+
if selection == "persistent":
13011299
command.set_persistent_git_options(C=".git")
13021300
elif selection == "git-dir-option":
1303-
command(git_dir=".git")
1304-
output = Path(repo.git_dir if selection in ("one-shot", "persistent") else repo.working_dir)
1301+
command.set_persistent_git_options(git_dir=".git")
1302+
output = Path(repo.git_dir if selection == "persistent" else repo.working_dir)
13051303
output /= "output.txt"
13061304
baseline.hook("run", "pre-commit")
13071305
expected = output.read_text(encoding="utf-8")
13081306
output.unlink()
13091307
run_commit_hook("pre-commit", index)
13101308
self.assertEqual(output.read_text(encoding="utf-8"), expected)
13111309

1312-
metadata.git.set_persistent_git_options()
1313-
metadata.git(C="missing")
1314-
with self.assertRaises(GitCommandError):
1315-
run_commit_hook("pre-commit", index)
1316-
self.assertEqual(metadata.git.rev_parse("--git-dir"), str(metadata.git_dir))
1317-
13181310
def test_pre_commit_hook_fail(self):
13191311
with fixture_repo("index.sh", "hook-fail", write=True) as repo:
13201312
with self.assertRaises(HookExecutionError) as caught:

‎test/test_remote.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -623,10 +623,11 @@ def test_push_resolves_revision_source_with_call_environment(self, rw_repo):
623623
self.assertEqual(info.local_hash, parent.hexsha)
624624
self.assertEqual(rw_repo.heads.snapshot.commit, parent)
625625

626+
# Discarding the configured wrapper must not affect the push.
626627
rw_repo.git(no_replace_objects=True)
627-
(info,) = remote.push("HEAD~1:refs/heads/snapshot_once")
628-
self.assertIsNone(info.local_hash)
629-
self.assertEqual(rw_repo.heads.snapshot_once.commit, parent)
628+
(info,) = remote.push("HEAD~1:refs/heads/snapshot_with_replace")
629+
self.assertEqual(info.local_hash, parent.parents[0].hexsha)
630+
self.assertEqual(rw_repo.heads.snapshot_with_replace.commit, parent.parents[0])
630631

631632
@with_rw_repo("HEAD", bare=False)
632633
def test_push_revision_sources(self, rw_repo):

0 commit comments

Comments
 (0)