From: Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> Date: Mon, 28 Sep 2020 19:18:39 +0000 (-0700) Subject: bpo-40105: ZipFile truncate in append mode with shorter comment (GH-19337) X-Git-Tag: v3.8.7rc1~148 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=e4008404fbc0002c49becc565d42e93eca11dd75;p=thirdparty%2FPython%2Fcpython.git bpo-40105: ZipFile truncate in append mode with shorter comment (GH-19337) (cherry picked from commit ff9147d93b868f0e13b9fe14e2a76c2879f6787b) Co-authored-by: Jan Mazur <16736821+mzr@users.noreply.github.com> --- diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py index e2e37a177041..31153445697f 100644 --- a/Lib/test/test_zipfile.py +++ b/Lib/test/test_zipfile.py @@ -1844,11 +1844,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") diff --git a/Lib/zipfile.py b/Lib/zipfile.py index 73e89666309f..e95e2b2d452d 100644 --- a/Lib/zipfile.py +++ b/Lib/zipfile.py @@ -1942,6 +1942,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 index 000000000000..f71a7a1e697a --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-04-03-16-13-59.bpo-40105.hfM2c0.rst @@ -0,0 +1,2 @@ +ZipFile truncates files to avoid corruption when a shorter comment is provided +in append ("a") mode. Patch by Jan Mazur.