]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-40105: ZipFile truncate in append mode with shorter comment (GH-19337)
authorJan Mazur <16736821+mzr@users.noreply.github.com>
Mon, 28 Sep 2020 18:53:33 +0000 (20:53 +0200)
committerGitHub <noreply@github.com>
Mon, 28 Sep 2020 18:53:33 +0000 (21:53 +0300)
Lib/test/test_zipfile.py
Lib/zipfile.py
Misc/NEWS.d/next/Library/2020-04-03-16-13-59.bpo-40105.hfM2c0.rst [new file with mode: 0644]

index 2851051425bf12f942d8640788970add98dfe80a..687e43df780d65366ef845d66cf263a4fe8aae98 100644 (file)
@@ -1856,11 +1856,14 @@ class OtherTests(unittest.TestCase):
             self.assertEqual(zipf.comment, b"an updated comment")
 
         # check that comments are correctly shortened in append mode
+        # and the file is indeed truncated
         with zipfile.ZipFile(TESTFN,mode="w") as zipf:
             zipf.comment = b"original comment that's longer"
             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:
             zipf.comment = b"shorter comment"
+        self.assertTrue(original_zip_size > os.path.getsize(TESTFN))
         with zipfile.ZipFile(TESTFN,mode="r") as zipf:
             self.assertEqual(zipf.comment, b"shorter comment")
 
index 915698f9e0588936f7adb1b0394860819fad8f73..816f8582bbf6d5949537f1e42e1173b67bc4c19a 100644 (file)
@@ -1918,6 +1918,8 @@ class ZipFile:
                              centDirSize, centDirOffset, len(self._comment))
         self.fp.write(endrec)
         self.fp.write(self._comment)
+        if self.mode == "a":
+            self.fp.truncate()
         self.fp.flush()
 
     def _fpclose(self, fp):
diff --git a/Misc/NEWS.d/next/Library/2020-04-03-16-13-59.bpo-40105.hfM2c0.rst b/Misc/NEWS.d/next/Library/2020-04-03-16-13-59.bpo-40105.hfM2c0.rst
new file mode 100644 (file)
index 0000000..f71a7a1
--- /dev/null
@@ -0,0 +1,2 @@
+ZipFile truncates files to avoid corruption when a shorter comment is provided
+in append ("a") mode. Patch by Jan Mazur.