Skip to content

gh-108111: Flush gzip write buffer before seeking, fixing bad writes #108341

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 5 commits into from
Aug 24, 2023
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
3 changes: 3 additions & 0 deletions Lib/gzip.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,9 @@ def seekable(self):

def seek(self, offset, whence=io.SEEK_SET):
if self.mode == WRITE:
self._check_not_closed()
# Flush buffer to ensure validity of self.offset
self._buffer.flush()
if whence != io.SEEK_SET:
if whence == io.SEEK_CUR:
offset = self.offset + offset
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_gzip.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,18 @@ def flush(self, mode=-1):
]
self.assertEqual(fc.modes, expected_modes)

def test_write_seek_write(self):
# Make sure that offset is up-to-date before seeking
# See issue GH-108111
b = io.BytesIO()
message = b"important message here."
with gzip.GzipFile(fileobj=b, mode='w') as f:
f.write(message)
f.seek(len(message))
f.write(message)
data = b.getvalue()
self.assertEqual(gzip.decompress(data), message * 2)


class TestOpen(BaseTest):
def test_binary_modes(self):
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,7 @@ Colin Marc
Vincent Marchetti
David Marek
Doug Marien
Chris Markiewicz
Sven Marnach
John Marshall
Alex Martelli
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a regression introduced in GH-101251 for 3.12, resulting in an incorrect
offset calculation in :meth:`gzip.GzipFile.seek`.