Extract a .zip/.tar.gz archive to a folder.
776417
def unpack_archive(archive_format, archive_path, source_path):
    """"""
    if archive_format not in ('zip', 'tar'):
        raise ValueError('Unknown archive format "%s".' % archive_format)
    if archive_format == 'zip':
        with zipfile.ZipFile(archive_path) as archive:
            archive.extractall(source_path)
    if archive_format == 'tar':
        with tarfile.open(archive_path) as archive:
            archive.extractall(source_path)
745886
def _extract_to_tempdir(archive_filename):
    """"""
    if not os.path.exists(archive_filename):
        raise Exception("Archive '%s' does not exist" % (archive_filename))

    tempdir = tempfile.mkdtemp(prefix="metaextract_")
    current_cwd = os.getcwd()
    try:
        if tarfile.is_tarfile(archive_filename):
            with tarfile.open(archive_filename) as f:
                f.extractall(tempdir)
        elif zipfile.is_zipfile(archive_filename):
            with zipfile.ZipFile(archive_filename) as f:
                f.extractall(tempdir)
        else:
            raise Exception("Can not extract '%s'. "
                            "Not a tar or zip file" % archive_filename)
        os.chdir(tempdir)
        yield tempdir
    finally:
        os.chdir(current_cwd)
        shutil.rmtree(tempdir)
279794
def extract_archive(client, archive_path, extract_path=None):
    
    command = 'tar -xf {path}'.format(path=archive_path)

    if extract_path:
        command += ' -C {extract_path}'.format(extract_path=extract_path)

    out = execute_ssh_command(client, command)
    return out
245962
def _unpack_zipfile(filename, extract_dir):
    
    try:
        import zipfile
    except ImportError:
        raise ReadError('zlib not supported, cannot unpack this archive.')

    if not zipfile.is_zipfile(filename):
        raise ReadError("%s is not a zip file" % filename)

    zip = zipfile.ZipFile(filename)
    try:
        for info in zip.infolist():
            name = info.filename

            # don't extract absolute paths or ones with .. in them
            if name.startswith('/') or '..' in name:
                continue

            target = os.path.join(extract_dir, *name.split('/'))
            if not target:
                continue

            _ensure_directory(target)
            if not name.endswith('/'):
                # file
                data = zip.read(info.filename)
                f = open(target, 'wb')
                try:
                    f.write(data)
                finally:
                    f.close()
                    del data
    finally:
        zip.close()
1264280
def extract_files(file_paths, target_path):
        
        os.makedirs(target_path, exist_ok=True)
        extracted = []

        for file_path in file_paths:
            with tarfile.open(file_path, 'r') as archive:
                archive.extractall(target_path)

            file_name = os.path.splitext(os.path.basename(file_path))[0]
            extracted.append(os.path.join(target_path, file_name))

        return extracted
878033
def create_archive(path, remove_path=True):
    
    root_path = os.path.dirname(path)
    relative_path = os.path.basename(path)
    archive_path = path + ".tar.gz"

    cmd = [["tar", "-C", root_path, "-czf", archive_path, relative_path]]
    call(cmd, env=SAFE_ENV)
    if remove_path:
        fs.remove(path)
    return archive_path
1001641
def extract_cab (archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    cmdlist = [cmd, '-d', outdir]
    if verbosity > 0:
        cmdlist.append('-v')
    cmdlist.append(archive)
    return cmdlist
826513
def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    return _extract(archive, compression, cmd, 'alone', verbosity, outdir)
97357
def extract_tar(tar_path, target_folder):
    
    with tarfile.open(tar_path, 'r') as archive:
        archive.extractall(target_folder)
706993
def extract_cpio (archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    cmdlist = [util.shell_quote(cmd), '--extract', '--make-directories',
        '--preserve-modification-time']
    if sys.platform.startswith('linux') and not cmd.endswith('bsdcpio'):
        cmdlist.extend(['--no-absolute-filenames',
        '--force-local', '--nonmatching', r'"*\.\.*"'])
    if verbosity > 1:
        cmdlist.append('-v')
    cmdlist.extend(['<', util.shell_quote(os.path.abspath(archive))])
    return (cmdlist, {'cwd': outdir, 'shell': True})
7673
def uncompress_archives(file_names, temp_dir):
    
    result = []
    for filename in file_names:
        if filename.endswith(".tar") or filename.endswith(".tar.gz") or filename.endswith(".tar.bz2"):
            obj = tarfile.open(filename, "r")
            extracted_file_names = []
            for j, member in enumerate(obj.getmembers()):
                obj.extract(member, temp_dir)
                extracted_filename = os.path.join(temp_dir, obj.getnames()[j])
                extracted_file_names.append(extracted_filename)
                archives[extracted_filename] = filename
            result.extend(extracted_file_names[:])
        elif filename.endswith(".zip"):
            obj = zipfile.ZipFile(filename)
            extracted_file_names = []
            for j, info in enumerate(obj.infolist()):
                obj.extract(info, path=temp_dir)
                extracted_filename = os.path.join(temp_dir, obj.namelist()[j])
                extracted_file_names.append(extracted_filename)
                archives[extracted_filename] = filename
            result.extend(extracted_file_names[:])
        else:
            result.append(filename)

    return result
688441
def compress_to(self, archive_path=None):
        
        if archive_path is None:
            archive = tempfile.NamedTemporaryFile(delete=False)
            tar_args = ()
            tar_kwargs = {'fileobj': archive}
            _return = archive.name
        else:
            tar_args = (archive_path)
            tar_kwargs = {}
            _return = archive_path
        tar_kwargs.update({'mode': 'w:gz'})
        with closing(tarfile.open(*tar_args, **tar_kwargs)) as tar:
            tar.add(self.path, arcname=self.file)

        return _return
239998
def _extract_archive(file, target_dir):
    
    if file.endswith('.gz') or file.endswith('.tar') or file.endswith('.tgz'):
        archive = tarfile.open(file, 'r')
    elif file.endswith('.zip'):
        archive = zipfile.ZipFile(file, 'r')
    else:
        raise Exception('Unrecognized file type: ' + file)
    archive.extractall(path=target_dir)
    archive.close()
228016
def extract_xz(archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    return _extract(archive, compression, cmd, 'xz', verbosity, outdir)
542645
def _recompress_archive(archive, verbosity=0, interactive=True):
    """"""
    format, compression = get_archive_format(archive)
    if compression:
        # only recompress the compression itself (eg. for .tar.xz)
        format = compression
    tmpdir = util.tmpdir()
    tmpdir2 = util.tmpdir()
    base, ext = os.path.splitext(os.path.basename(archive))
    archive2 = util.get_single_outfile(tmpdir2, base, extension=ext)
    try:
        # extract
        kwargs = dict(verbosity=verbosity, format=format, outdir=tmpdir)
        path = _extract_archive(archive, **kwargs)
        # compress to new file
        olddir = os.getcwd()
        os.chdir(path)
        try:
            kwargs = dict(verbosity=verbosity, interactive=interactive, format=format)
            files = tuple(os.listdir(path))
            _create_archive(archive2, files, **kwargs)
        finally:
            os.chdir(olddir)
        # check file sizes and replace if new file is smaller
        filesize = util.get_filesize(archive)
        filesize2 = util.get_filesize(archive2)
        if filesize2 < filesize:
            # replace file
            os.remove(archive)
            shutil.move(archive2, archive)
            diffsize = filesize - filesize2
            return "... recompressed file is now %s smaller." % util.strsize(diffsize)
    finally:
        shutil.rmtree(tmpdir, onerror=rmtree_log_error)
        shutil.rmtree(tmpdir2, onerror=rmtree_log_error)
    return "... recompressed file is not smaller, leaving archive as is."
1155498
function(archive, env) {

    // The extraction command
    var extract = [
      'tar',
      '-zxvf',
      archive,
      '-C',
      '/media',
      '&&',
      'mv',
      '/media/files_' + env + '/*',
      '/media'
    ];

    // Extract and remove
    return run('usermap', extract)
    .then(function() {
      return run('rm', ['-rf', '/media/files_' + env]);
    })
    .then(function() {
      return run('rm', ['-f', archive]);
    });

  }
300643
def extract_tar (archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    cmdlist = [cmd, '--extract']
    add_tar_opts(cmdlist, compression, verbosity)
    cmdlist.extend(["--file", archive, '--directory', outdir])
    return cmdlist