+LOG = logging.getLogger('swc-windows-installer')
+LOG.addHandler(logging.StreamHandler())
+LOG.setLevel(logging.INFO)
+
+
+if sys.version_info >= (3, 0): # Python 3
+ open3 = open
+else:
+ def open3(file, mode='r', newline=None):
+ if newline:
+ if newline != '\n':
+ raise NotImplementedError(newline)
+ f = open(file, mode + 'b')
+ else:
+ f = open(file, mode)
+ return f
+
+
+def download(url, sha1):
+ """Download a file and verify it's hash"""
+ LOG.debug('download {}'.format(url))
+ r = _urlopen(url)
+ byte_content = r.read()
+ download_sha1 = hashlib.sha1(byte_content).hexdigest()
+ if download_sha1 != sha1:
+ raise ValueError(
+ 'downloaded {!r} has the wrong SHA-1 hash: {} != {}'.format(
+ url, download_sha1, sha1))
+ LOG.debug('SHA-1 for {} matches the expected {}'.format(url, sha1))
+ return byte_content
+
+
+def splitall(path):
+ """Split a path into a list of components
+
+ >>> splitall('nano-2.2.6/doc/Makefile.am')
+ ['nano-2.2.6', 'doc', 'Makefile.am']
+ """
+ parts = []
+ while True:
+ head, tail = os.path.split(path)
+ if tail:
+ parts.insert(0, tail)
+ elif head:
+ parts.insert(0, head)
+ break
+ else:
+ break
+ path = head
+ return parts
+
+
+def transform(tarinfo, strip_components=0):
+ """Transform TarInfo objects for extraction"""
+ path_components = splitall(tarinfo.name)
+ try:
+ tarinfo.name = os.path.join(*path_components[strip_components:])
+ except TypeError:
+ if len(path_components) <= strip_components:
+ return None
+ raise
+ return tarinfo
+
+
+def tar_install(url, sha1, install_directory, compression='*',
+ strip_components=0):
+ """Download and install a tar bundle"""
+ if not os.path.isdir(install_directory):
+ tar_bytes = download(url=url, sha1=sha1)
+ tar_io = _BytesIO(tar_bytes)
+ filename = os.path.basename(url)
+ mode = 'r:{}'.format(compression)
+ tar_file = tarfile.open(filename, mode, tar_io)
+ LOG.info('installing {} into {}'.format(url, install_directory))
+ os.makedirs(install_directory)
+ members = [
+ transform(tarinfo=tarinfo, strip_components=strip_components)
+ for tarinfo in tar_file]
+ tar_file.extractall(
+ path=install_directory,
+ members=[m for m in members if m is not None])
+ else:
+ LOG.info('existing installation at {}'.format(install_directory))
+
+
+def zip_install(url, sha1, install_directory):
+ """Download and install a zipped bundle"""
+ if not os.path.isdir(install_directory):
+ zip_bytes = download(url=url, sha1=sha1)
+ zip_io = _BytesIO(zip_bytes)
+ zip_file = zipfile.ZipFile(zip_io)
+ LOG.info('installing {} into {}'.format(url, install_directory))
+ os.makedirs(install_directory)
+ zip_file.extractall(install_directory)
+ else:
+ LOG.info('existing installation at {}'.format(install_directory))
+
+