Skip to content

Commit 4bea462

Browse files
miss-islingtonlpyu001StanFromIreland
authored
[3.14] gh-156078: Prevent ZipFile.mkdir() during an active write (GH-156079) (#160478)
Fix `ZipFile.mkdir()` so that it raises `ValueError` when another writable member handle returned by `ZipFile.open(..., mode="w")` is still open. (cherry picked from commit dc78afe) Co-authored-by: Pengyu Lee <lipengyu@kylinos.cn> Co-authored-by: Stan Ulbrych <stan@python.org>
1 parent 75e8f80 commit 4bea462

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
@@ -2447,6 +2447,8 @@ def test_open_conflicting_handles(self):
24472447
zipf.writestr('str', 'abcde')
24482448
with self.assertRaises(ValueError):
24492449
zipf.write(__file__, 'file')
2450+
with self.assertRaises(ValueError):
2451+
zipf.mkdir('directory')
24502452
with self.assertRaises(ValueError):
24512453
zipf.close()
24522454
w1.write(msg2)
@@ -3476,6 +3478,9 @@ def test_mkdir(self):
34763478
zf.extractall(target)
34773479
self.assertEqual(set(os.listdir(target)), {"directory", "directory2", "directory3", "directory4"})
34783480

3481+
with self.assertRaises(ValueError):
3482+
zf.mkdir("closed")
3483+
34793484
def test_create_directory_with_write(self):
34803485
with zipfile.ZipFile(TESTFN, "w") as zf:
34813486
zf.writestr(zipfile.ZipInfo('directory/'), '')

‎Lib/zipfile/__init__.py‎

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

2085+
if not self.fp:
2086+
raise ValueError(
2087+
"Attempt to write to ZIP archive that was already closed"
2088+
)
2089+
if self._writing:
2090+
raise ValueError(
2091+
"Can't write to ZIP archive while an open writing handle exists."
2092+
)
2093+
20852094
with self._lock:
20862095
if self._seekable:
20872096
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)