Skip to content

Commit dc78afe

Browse files
gh-156078: Prevent ZipFile.mkdir() during an active write (#156079)
Fix `ZipFile.mkdir()` so that it raises `ValueError` when another writable member handle returned by `ZipFile.open(..., mode="w")` is still open. Co-authored-by: Stan Ulbrych <stan@python.org>
1 parent 0ba58e7 commit dc78afe

3 files changed

Lines changed: 16 additions & 0 deletions

File tree

‎Lib/test/test_zipfile/test_core.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4615,6 +4615,8 @@ def test_open_conflicting_handles(self):
46154615
zipf.writestr('str', 'abcde')
46164616
with self.assertRaises(ValueError):
46174617
zipf.write(__file__, 'file')
4618+
with self.assertRaises(ValueError):
4619+
zipf.mkdir('directory')
46184620
with self.assertRaises(ValueError):
46194621
zipf.close()
46204622
w1.write(msg2)
@@ -5646,6 +5648,9 @@ def test_mkdir(self):
56465648
zf.extractall(target)
56475649
self.assertEqual(set(os.listdir(target)), {"directory", "directory2", "directory3", "directory4"})
56485650

5651+
with self.assertRaises(ValueError):
5652+
zf.mkdir("closed")
5653+
56495654
def test_create_directory_with_write(self):
56505655
with zipfile.ZipFile(TESTFN, "w") as zf:
56515656
zf.writestr(zipfile.ZipInfo('directory/'), '')

‎Lib/zipfile/__init__.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2630,6 +2630,15 @@ def mkdir(self, zinfo_or_directory_name, mode=511):
26302630
else:
26312631
raise TypeError("Expected type str or ZipInfo")
26322632

2633+
if not self.fp:
2634+
raise ValueError(
2635+
"Attempt to write to ZIP archive that was already closed"
2636+
)
2637+
if self._writing:
2638+
raise ValueError(
2639+
"Can't write to ZIP archive while an open writing handle exists."
2640+
)
2641+
26332642
with self._lock:
26342643
if self._seekable:
26352644
self.fp.seek(self.start_dir)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:meth:`zipfile.ZipFile.mkdir` now raises :exc:`ValueError` when the archive
2+
is closed or when a writable member handle is open.

0 commit comments

Comments
 (0)