mirror of
https://github.com/python/cpython.git
synced 2025-08-02 16:13:13 +00:00
bpo-40105: ZipFile truncate in append mode with shorter comment (GH-19337)
(cherry picked from commit ff9147d93b
)
Co-authored-by: Jan Mazur <16736821+mzr@users.noreply.github.com>
This commit is contained in:
parent
bdf46bc7e1
commit
048f54dc75
3 changed files with 7 additions and 0 deletions
|
@ -1855,11 +1855,14 @@ class OtherTests(unittest.TestCase):
|
||||||
self.assertEqual(zipf.comment, b"an updated comment")
|
self.assertEqual(zipf.comment, b"an updated comment")
|
||||||
|
|
||||||
# check that comments are correctly shortened in append mode
|
# check that comments are correctly shortened in append mode
|
||||||
|
# and the file is indeed truncated
|
||||||
with zipfile.ZipFile(TESTFN,mode="w") as zipf:
|
with zipfile.ZipFile(TESTFN,mode="w") as zipf:
|
||||||
zipf.comment = b"original comment that's longer"
|
zipf.comment = b"original comment that's longer"
|
||||||
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
|
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
|
||||||
|
original_zip_size = os.path.getsize(TESTFN)
|
||||||
with zipfile.ZipFile(TESTFN,mode="a") as zipf:
|
with zipfile.ZipFile(TESTFN,mode="a") as zipf:
|
||||||
zipf.comment = b"shorter comment"
|
zipf.comment = b"shorter comment"
|
||||||
|
self.assertTrue(original_zip_size > os.path.getsize(TESTFN))
|
||||||
with zipfile.ZipFile(TESTFN,mode="r") as zipf:
|
with zipfile.ZipFile(TESTFN,mode="r") as zipf:
|
||||||
self.assertEqual(zipf.comment, b"shorter comment")
|
self.assertEqual(zipf.comment, b"shorter comment")
|
||||||
|
|
||||||
|
|
|
@ -1918,6 +1918,8 @@ class ZipFile:
|
||||||
centDirSize, centDirOffset, len(self._comment))
|
centDirSize, centDirOffset, len(self._comment))
|
||||||
self.fp.write(endrec)
|
self.fp.write(endrec)
|
||||||
self.fp.write(self._comment)
|
self.fp.write(self._comment)
|
||||||
|
if self.mode == "a":
|
||||||
|
self.fp.truncate()
|
||||||
self.fp.flush()
|
self.fp.flush()
|
||||||
|
|
||||||
def _fpclose(self, fp):
|
def _fpclose(self, fp):
|
||||||
|
|
|
@ -0,0 +1,2 @@
|
||||||
|
ZipFile truncates files to avoid corruption when a shorter comment is provided
|
||||||
|
in append ("a") mode. Patch by Jan Mazur.
|
Loading…
Add table
Add a link
Reference in a new issue