Skip to content

[3.8] bpo-40105: ZipFile truncate in append mode with shorter comment (GH-19337) #22437

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
bpo-40105: ZipFile truncate in append mode with shorter comment (GH-1…
…9337)

(cherry picked from commit ff9147d)

Co-authored-by: Jan Mazur <16736821+mzr@users.noreply.github.com>
  • Loading branch information
mzr authored and miss-islington committed Sep 28, 2020
commit bf9ac46ffbf312c7a294fa75b8e1dbf98ef0c7ea
3 changes: 3 additions & 0 deletions Lib/test/test_zipfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1844,11 +1844,14 @@ def test_comments(self):
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")

Expand Down
2 changes: 2 additions & 0 deletions Lib/zipfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1942,6 +1942,8 @@ def _write_end_record(self):
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):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ZipFile truncates files to avoid corruption when a shorter comment is provided
in append ("a") mode. Patch by Jan Mazur.