Skip to content

bpo-44289: Keep argument file object's current position in tarfile.is_tarfile #26488

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 4 commits into from
Feb 9, 2022
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
2 changes: 2 additions & 0 deletions Lib/tarfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -2484,7 +2484,9 @@ def is_tarfile(name):
"""
try:
if hasattr(name, "read"):
pos = name.tell()
t = open(fileobj=name)
name.seek(pos)
else:
t = open(name)
t.close()
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_tarfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,18 @@ def test_is_tarfile_valid(self):
with open(self.tarname, "rb") as fobj:
self.assertTrue(tarfile.is_tarfile(io.BytesIO(fobj.read())))

def test_is_tarfile_keeps_position(self):
# Test for issue44289: tarfile.is_tarfile() modifies
# file object's current position
with open(self.tarname, "rb") as fobj:
tarfile.is_tarfile(fobj)
self.assertEqual(fobj.tell(), 0)

with open(self.tarname, "rb") as fobj:
file_like = io.BytesIO(fobj.read())
tarfile.is_tarfile(file_like)
self.assertEqual(file_like.tell(), 0)

def test_empty_tarfile(self):
# Test for issue6123: Allow opening empty archives.
# This test checks if tarfile.open() is able to open an empty tar
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix an issue with :meth:`~tarfile.is_tarfile` method when using *fileobj* argument: position in the *fileobj* was advanced forward which made it unreadable with :meth:`tarfile.TarFile.open`.