Skip to content

Commit bfe8238

Browse files
committed
Move repack() state checks under the lock and merge the handle errors
The fp/_writing/_fileRefCnt checks guarded state that repack() then mutates inside `with self._lock`, so the check and the `_writing = True` it gates were not atomic. Move them into the lock. The writing-handle and reading-handle errors describe the same condition, so state it once.
1 parent 82d68c7 commit bfe8238

2 files changed

Lines changed: 9 additions & 13 deletions

File tree

Doc/library/zipfile.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -583,7 +583,7 @@ ZipFile objects
583583
Rewrites the archive to remove unreferenced local file entries, shrinking
584584
its file size. The archive must be opened with mode ``'a'``, and any file
585585
object returned by :meth:`ZipFile.open` must be closed first, since
586-
repacking moves the member data those objects read from.
586+
repacking moves the member data such objects refer to.
587587

588588
If *removed* is provided, it must be a sequence of :class:`ZipInfo` objects
589589
representing the recently removed members, and only their corresponding

Lib/zipfile/__init__.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2397,20 +2397,16 @@ def repack(self, removed=None, *, strict_descriptor=True,
23972397
truncation."""
23982398
if self.mode != 'a':
23992399
raise ValueError("repack() requires mode 'a'")
2400-
if not self.fp:
2401-
raise ValueError(
2402-
"Attempt to write to ZIP archive that was already closed")
2403-
if self._writing:
2404-
raise ValueError(
2405-
"Can't write to ZIP archive while an open writing handle exists"
2406-
)
2407-
if self._fileRefCnt > 1:
2408-
raise ValueError(
2409-
"Can't repack the ZIP archive while an open reading handle "
2410-
"exists. Close the reading handle before repacking."
2411-
)
24122400

24132401
with self._lock:
2402+
if not self.fp:
2403+
raise ValueError(
2404+
"Attempt to write to ZIP archive that was already closed")
2405+
if self._writing or self._fileRefCnt > 1:
2406+
raise ValueError(
2407+
"Can't repack ZIP archive while an open handle exists"
2408+
)
2409+
24142410
self._writing = True
24152411
try:
24162412
repacker = _ZipRepacker(

0 commit comments

Comments
 (0)