misc: update download() function

-require 'dst' parameter
-allow 'dst' parameter to be dir or dest file
-use contextlib.suppress instead of try/except/pass

Signed-off-by: Dan Streetman <ddstreet@canonical.com>
This commit is contained in:
Dan Streetman 2020-03-25 15:47:33 -04:00
parent 3d0921ee54
commit 248cf38d79

View File

@ -29,6 +29,7 @@ import os
import shutil import shutil
import sys import sys
from contextlib import suppress
from subprocess import check_output, CalledProcessError from subprocess import check_output, CalledProcessError
from urllib.parse import urlparse from urllib.parse import urlparse
from urllib.request import urlopen from urllib.request import urlopen
@ -225,22 +226,20 @@ def verify_file_checksum(pathname, alg, checksum, size=0):
return match return match
def download(src, dst=None, size=0): def download(src, dst, size=0):
""" download/copy a file/url to local file """ """ download/copy a file/url to local file """
filename = os.path.basename(urlparse(src).path) filename = os.path.basename(urlparse(src).path)
if not dst: if os.path.isdir(dst):
dst = filename dst = os.path.join(dst, filename)
with urlopen(src) as fsrc, open(dst, 'wb') as fdst: with urlopen(src) as fsrc, open(dst, 'wb') as fdst:
url = fsrc.geturl() url = fsrc.geturl()
Logger.debug(f"Using URL: {url}") Logger.debug(f"Using URL: {url}")
if not size: if not size:
try: with suppress(AttributeError, TypeError, ValueError):
size = int(fsrc.info().get('Content-Length')) size = int(fsrc.info().get('Content-Length'))
except (AttributeError, TypeError, ValueError):
pass
hostname = urlparse(url).hostname hostname = urlparse(url).hostname
sizemb = ' (%0.3f MiB)' % (size / 1024.0 / 1024) if size else '' sizemb = ' (%0.3f MiB)' % (size / 1024.0 / 1024) if size else ''