Use Python's zipfile, if available (#24556)

* Style fixes

* Use Python's zipfile, if available

The compression libs are optional in Python. Rely on python as a
first attempt then fall back to `unzip`
This commit is contained in:
Betsy McPhail 2021-06-28 10:39:10 -04:00 committed by Peter Scheibel
parent f8782c46d7
commit 4a73bfc3b9

View file

@ -39,13 +39,31 @@ def _gunzip(archive_file):
f_out.write(f_in.read())
def _unzip(archive_file):
"""Try to use Python's zipfile, but extract in the current working
directory instead of in-place.
If unavailable, try unzip
Args:
archive_file (str): absolute path of the file to be decompressed
"""
try:
from zipfile import ZipFile
destination_abspath = os.getcwd()
with ZipFile(archive_file, 'r') as zf:
zf.extractall(destination_abspath)
except ImportError:
unzip = which('unzip', required=True)
unzip.add_default_arg('-q')
return unzip
def decompressor_for(path, extension=None):
"""Get the appropriate decompressor for a path."""
if ((extension and re.match(r'\.?zip$', extension)) or
path.endswith('.zip')):
unzip = which('unzip', required=True)
unzip.add_default_arg('-q')
return unzip
return _unzip
if extension and re.match(r'gz', extension):
return _gunzip
if extension and re.match(r'bz2', extension):