Skip to content

Commit a89d22a

Browse files
Issue #28449: tarfile.open() with mode "r" or "r:" now tries to open a tar
file with compression before trying to open it without compression. Otherwise it had 50% chance failed with ignore_zeros=True.
1 parent d1af5ef commit a89d22a

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

Lib/tarfile.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1549,7 +1549,9 @@ def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
15491549

15501550
if mode in ("r", "r:*"):
15511551
# Find out which *open() is appropriate for opening the file.
1552-
for comptype in cls.OPEN_METH:
1552+
def not_compressed(comptype):
1553+
return cls.OPEN_METH[comptype] == 'taropen'
1554+
for comptype in sorted(cls.OPEN_METH, key=not_compressed):
15531555
func = getattr(cls, cls.OPEN_METH[comptype])
15541556
if fileobj is not None:
15551557
saved_pos = fileobj.tell()

Lib/test/test_tarfile.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import io
44
from hashlib import md5
55
from contextlib import contextmanager
6+
from random import Random
67

78
import unittest
89
import unittest.mock
@@ -349,12 +350,17 @@ def test_null_tarfile(self):
349350

350351
def test_ignore_zeros(self):
351352
# Test TarFile's ignore_zeros option.
353+
# generate 512 pseudorandom bytes
354+
data = Random(0).getrandbits(512*8).to_bytes(512, 'big')
352355
for char in (b'\0', b'a'):
353356
# Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
354357
# are ignored correctly.
355358
with self.open(tmpname, "w") as fobj:
356359
fobj.write(char * 1024)
357-
fobj.write(tarfile.TarInfo("foo").tobuf())
360+
tarinfo = tarfile.TarInfo("foo")
361+
tarinfo.size = len(data)
362+
fobj.write(tarinfo.tobuf())
363+
fobj.write(data)
358364

359365
tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
360366
try:

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,10 @@ Core and Builtins
113113
Library
114114
-------
115115

116+
- Issue #28449: tarfile.open() with mode "r" or "r:" now tries to open a tar
117+
file with compression before trying to open it without compression. Otherwise
118+
it had 50% chance failed with ignore_zeros=True.
119+
116120
- Issue #23262: The webbrowser module now supports Firefox 36+ and derived
117121
browsers. Based on patch by Oleg Broytman.
118122

0 commit comments

Comments
 (0)