Skip to content

Commit b5420ed

Browse files
mzrmiss-islington
authored andcommitted
bpo-40105: ZipFile truncate in append mode with shorter comment (pythonGH-19337)
(cherry picked from commit ff9147d) Co-authored-by: Jan Mazur <16736821+mzr@users.noreply.github.com>
1 parent bdf46bc commit b5420ed

File tree

3 files changed

+7
-0
lines changed

3 files changed

+7
-0
lines changed

Lib/test/test_zipfile.py

+3
Original file line numberDiff line numberDiff line change
@@ -1855,11 +1855,14 @@ def test_comments(self):
18551855
self.assertEqual(zipf.comment, b"an updated comment")
18561856

18571857
# check that comments are correctly shortened in append mode
1858+
# and the file is indeed truncated
18581859
with zipfile.ZipFile(TESTFN,mode="w") as zipf:
18591860
zipf.comment = b"original comment that's longer"
18601861
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1862+
original_zip_size = os.path.getsize(TESTFN)
18611863
with zipfile.ZipFile(TESTFN,mode="a") as zipf:
18621864
zipf.comment = b"shorter comment"
1865+
self.assertTrue(original_zip_size > os.path.getsize(TESTFN))
18631866
with zipfile.ZipFile(TESTFN,mode="r") as zipf:
18641867
self.assertEqual(zipf.comment, b"shorter comment")
18651868

Lib/zipfile.py

+2
Original file line numberDiff line numberDiff line change
@@ -1918,6 +1918,8 @@ def _write_end_record(self):
19181918
centDirSize, centDirOffset, len(self._comment))
19191919
self.fp.write(endrec)
19201920
self.fp.write(self._comment)
1921+
if self.mode == "a":
1922+
self.fp.truncate()
19211923
self.fp.flush()
19221924

19231925
def _fpclose(self, fp):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
ZipFile truncates files to avoid corruption when a shorter comment is provided
2+
in append ("a") mode. Patch by Jan Mazur.

0 commit comments

Comments
 (0)