Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e12c0b1

Browse files
author
Charles-François Natali
committed
Issue #12464: tempfile.TemporaryDirectory.cleanup() should not follow symlinks:
fix it. Patch by Petri Lehtinen.
2 parents 516c51c + def3543 commit e12c0b1

3 files changed

Lines changed: 26 additions & 1 deletion

File tree

Lib/tempfile.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -661,6 +661,7 @@ def __del__(self):
661661
_listdir = staticmethod(_os.listdir)
662662
_path_join = staticmethod(_os.path.join)
663663
_isdir = staticmethod(_os.path.isdir)
664+
_islink = staticmethod(_os.path.islink)
664665
_remove = staticmethod(_os.remove)
665666
_rmdir = staticmethod(_os.rmdir)
666667
_os_error = _os.error
@@ -672,7 +673,7 @@ def _rmtree(self, path):
672673
for name in self._listdir(path):
673674
fullname = self._path_join(path, name)
674675
try:
675-
isdir = self._isdir(fullname)
676+
isdir = self._isdir(fullname) and not self._islink(fullname)
676677
except self._os_error:
677678
isdir = False
678679
if isdir:

Lib/test/test_tempfile.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -964,6 +964,27 @@ def test_explicit_cleanup(self):
964964
finally:
965965
os.rmdir(dir)
966966

967+
@support.skip_unless_symlink
968+
def test_cleanup_with_symlink_to_a_directory(self):
969+
# cleanup() should not follow symlinks to directories (issue #12464)
970+
d1 = self.do_create()
971+
d2 = self.do_create()
972+
973+
# Symlink d1/foo -> d2
974+
os.symlink(d2.name, os.path.join(d1.name, "foo"))
975+
976+
# This call to cleanup() should not follow the "foo" symlink
977+
d1.cleanup()
978+
979+
self.assertFalse(os.path.exists(d1.name),
980+
"TemporaryDirectory %s exists after cleanup" % d1.name)
981+
self.assertTrue(os.path.exists(d2.name),
982+
"Directory pointed to by a symlink was deleted")
983+
self.assertEqual(os.listdir(d2.name), ['test.txt'],
984+
"Contents of the directory pointed to by a symlink "
985+
"were deleted")
986+
d2.cleanup()
987+
967988
@support.cpython_only
968989
def test_del_on_collection(self):
969990
# A TemporaryDirectory is deleted when garbage collected

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,9 @@ Core and Builtins
244244
Library
245245
-------
246246

247+
- Issue #12464: tempfile.TemporaryDirectory.cleanup() should not follow
248+
symlinks: fix it. Patch by Petri Lehtinen.
249+
247250
- Issue #8887: "pydoc somebuiltin.somemethod" (or help('somebuiltin.somemethod')
248251
in Python code) now finds the doc of the method.
249252

0 commit comments

Comments
 (0)