Skip to content

Commit fe74a6f

Browse files
authored
Merge pull request #2350 from jenshnielsen/jenshnielsen/agents/gitpython-repo-close-gc-optimization
Fix reference cycle in IndexFile._raise_exc and remove gc.collect()
2 parents 57a7865 + a8e210b commit fe74a6f

5 files changed

Lines changed: 35 additions & 13 deletions

File tree

‎doc/source/changes.rst‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,13 @@ API changes
225225
``os.path.expandvars`` if wanted; initial ``~`` expansion remains.
226226
``HIDE_WINDOWS_KNOWN_ERRORS`` and ``HIDE_WINDOWS_FREEZE_ERRORS`` are removed.
227227
``rmtree`` propagates filesystem errors rather than raising ``SkipTest``.
228+
* ``Repo.close()``, and therefore ``with Repo(...)`` and dropping a ``Repo``, no
229+
longer forces two full garbage collections on Windows. It still stops the
230+
repository's persistent Git processes. ``IndexFile.add()`` no longer leaves a
231+
reference cycle that kept the index and repository alive until the next
232+
collection. Close files and repositories you opened yourself before removing a
233+
repository on Windows; call ``gc.collect()`` only if your own objects are
234+
reachable solely through reference cycles.
228235

229236
3.2.1
230237
=====

‎git/index/base.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,12 @@ def _iter_expand_paths(self: "IndexFile", paths: Sequence[PathLike]) -> Iterator
464464
"""
465465

466466
def raise_exc(e: Exception) -> NoReturn:
467-
raise e
467+
try:
468+
raise e
469+
finally:
470+
# Break the exception -> traceback -> frame -> exception cycle, which
471+
# would otherwise keep this index and its repository alive.
472+
del e
468473

469474
r = str(self.repo.working_tree_dir)
470475
rs = r + os.sep

‎git/objects/submodule/base.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
__all__ = ["Submodule", "UpdateProgress"]
55

6-
import gc
76
import logging
87
import ntpath
98
import os
@@ -1553,8 +1552,7 @@ def remove(
15531552
if not dry_run:
15541553
self._clear_cache()
15551554
wtd = mod.working_tree_dir
1556-
del mod # Release file-handles (Windows).
1557-
gc.collect()
1555+
mod.close()
15581556
rmtree(str(wtd))
15591557
# END delete tree if possible
15601558
# END handle force

‎git/repo/base.py‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
__all__ = ["Repo"]
99

10-
import gc
1110
from io import BytesIO
1211
import logging
1312
import os
@@ -529,15 +528,7 @@ def close(self) -> None:
529528
"""
530529
if self.git:
531530
self.git.clear_cache()
532-
# Tempfiles objects on Windows are holding references to open files until
533-
# they are collected by the garbage collector, thus preventing deletion.
534-
# TODO: Find these references and ensure they are closed and deleted
535-
# synchronously rather than forcing a gc collection.
536-
if sys.platform == "win32":
537-
gc.collect()
538531
gitdb.util.mman.collect()
539-
if sys.platform == "win32":
540-
gc.collect()
541532

542533
def __eq__(self, rhs: object) -> bool:
543534
if isinstance(rhs, Repo):

‎test/test_index.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44
# 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
55

66
import contextlib
7+
import gc
78
import logging
89
import os
910
import os.path as osp
1011
import sys
12+
import weakref
1113
from itertools import product
1214
from pathlib import Path
1315
from stat import S_ISLNK, ST_MODE
@@ -52,6 +54,25 @@ def test_staged_legacy_filename_and_blob_bytes():
5254
}
5355

5456

57+
def test_adding_a_file_does_not_keep_the_repository_alive():
58+
# Repo.close() does not force a garbage collection, so staging must not leave a
59+
# reference cycle that delays releasing a dropped repository's Git processes.
60+
with fixture_repo("index.sh", "file", "testfile.txt", "content of testfile", write=True) as owner:
61+
gc_was_enabled = gc.isenabled()
62+
gc.disable()
63+
try:
64+
with mock.patch.object(gc, "collect") as collect:
65+
repo = Repo(owner.working_dir)
66+
repo.index.add(["testfile.txt"])
67+
dropped = weakref.ref(repo)
68+
del repo
69+
assert dropped() is None
70+
collect.assert_not_called()
71+
finally:
72+
if gc_was_enabled:
73+
gc.enable()
74+
75+
5576
@pytest.mark.skipif(os.name == "nt", reason="Windows symlink targets are Unicode paths")
5677
def test_staging_preserves_non_utf8_symlink_targets():
5778
if not symlinks_supported():

0 commit comments

Comments
 (0)