Skip to content

Commit f1cd4cb

Browse files
authored
Merge pull request #7608 from uranusjr/global-cleanup
Delay TempDirectory.delete resolution to cleanup
2 parents ea7def8 + 35377c9 commit f1cd4cb

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

src/pip/_internal/utils/temp_dir.py

+12-8
Original file line numberDiff line numberDiff line change
@@ -107,13 +107,10 @@ def __init__(
107107
):
108108
super(TempDirectory, self).__init__()
109109

110-
if path is None and delete is None:
111-
# If we were not given an explicit directory, and we were not given
112-
# an explicit delete option, then we'll default to deleting unless
113-
# the tempdir_registry says otherwise.
114-
delete = True
115-
if _tempdir_registry:
116-
delete = _tempdir_registry.get_delete(kind)
110+
# If we were given an explicit directory, resolve delete option now.
111+
# Otherwise we wait until cleanup and see what tempdir_registry says.
112+
if path is not None and delete is None:
113+
delete = False
117114

118115
if path is None:
119116
path = self._create(kind)
@@ -145,7 +142,14 @@ def __enter__(self):
145142

146143
def __exit__(self, exc, value, tb):
147144
# type: (Any, Any, Any) -> None
148-
if self.delete:
145+
if self.delete is not None:
146+
delete = self.delete
147+
elif _tempdir_registry:
148+
delete = _tempdir_registry.get_delete(self.kind)
149+
else:
150+
delete = True
151+
152+
if delete:
149153
self.cleanup()
150154

151155
def _create(self, kind):

tests/unit/test_utils_temp_dir.py

+14
Original file line numberDiff line numberDiff line change
@@ -234,3 +234,17 @@ def test_tempdir_registry(kind, delete, exists):
234234
path = d.path
235235
assert os.path.exists(path)
236236
assert os.path.exists(path) == exists
237+
238+
239+
@pytest.mark.parametrize("should_delete", [True, False])
240+
def test_tempdir_registry_lazy(should_delete):
241+
"""
242+
Test the registry entry can be updated after a temp dir is created,
243+
to change whether a kind should be deleted or not.
244+
"""
245+
with tempdir_registry() as registry:
246+
with TempDirectory(delete=None, kind="test-for-lazy") as d:
247+
path = d.path
248+
registry.set_delete("test-for-lazy", should_delete)
249+
assert os.path.exists(path)
250+
assert os.path.exists(path) == (not should_delete)

0 commit comments

Comments
 (0)