Unzip filename to a temporary directory, set to the cwd.

    The unzipped target is cleaned up after.
162095
def archive_context(filename):
    
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        with ContextualZipFile(filename) as archive:
            archive.extractall()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir)
540371
def unpack_zipfile(filename):
    """"""
    with open(filename, "rb") as fzip:
        z = zipfile.ZipFile(fzip)
        for name in z.namelist():
            print(("      extracting {}".format(name)))
            ensure_dirs(name)
            z.extract(name)
1291508
public static void unzip(String compressedFileName, String destinationDir) {
        //strip everything except the applications name
        String dirName = null;
        // checks to see if there is a dash "-" in the filename of the war. 
        String applicationName = compressedFileName.substring(compressedFileName.lastIndexOf("/"));
        int dashIndex = applicationName.indexOf('-');
        if (dashIndex != -1) {
            //strip everything except the applications name
            dirName = compressedFileName.substring(0, dashIndex);
        } else {
            //grab every char up to the last '.'
            dirName = compressedFileName.substring(0, compressedFileName.lastIndexOf('.'));
        }
        log.debug("Directory: {}", dirName);
        //String tmpDir = System.getProperty("java.io.tmpdir");
        File zipDir = new File(compressedFileName);
        File parent = zipDir.getParentFile();
        log.debug("Parent: {}", (parent != null ? parent.getName() : null));
        //File tmpDir = new File(System.getProperty("java.io.tmpdir"), dirName);
        File tmpDir = new File(destinationDir);
        // make the war directory
        log.debug("Making directory: {}", tmpDir.mkdirs());
        ZipFile zf = null;
        try {
            zf = new ZipFile(compressedFileName);
            Enumeration<?> e = zf.entries();
            while (e.hasMoreElements()) {
                ZipEntry ze = (ZipEntry) e.nextElement();
                log.debug("Unzipping {}", ze.getName());
                if (ze.isDirectory()) {
                    log.debug("is a directory");
                    File dir = new File(tmpDir + "/" + ze.getName());
                    Boolean tmp = dir.mkdir();
                    log.debug("{}", tmp);
                    continue;
                }

                // checks to see if a zipEntry contains a path
                // i.e. ze.getName() == "META-INF/MANIFEST.MF"
                // if this case is true, then we create the path first
                if (ze.getName().lastIndexOf("/") != -1) {
                    String zipName = ze.getName();
                    String zipDirStructure = zipName.substring(0, zipName.lastIndexOf("/"));
                    File completeDirectory = new File(tmpDir + "/" + zipDirStructure);
                    if (!completeDirectory.exists()) {
                        if (!completeDirectory.mkdirs()) {
                            log.error("could not create complete directory structure");
                        }
                    }
                }

                // creates the file
                FileOutputStream fout = new FileOutputStream(tmpDir + "/" + ze.getName());
                InputStream in = zf.getInputStream(ze);
                copy(in, fout);
                in.close();
                fout.close();
            }
            e = null;
        } catch (IOException e) {
            log.error("Errored unzipping", e);
            //log.warn("Exception {}", e);
        } finally {
            if (zf != null) {
                try {
                    zf.close();
                } catch (IOException e) {
                }
            }
        }
    }
39538
def clean(self):
        
        if not self._save_temp:
            if hasattr(self, '_written_files'):
                map(os.unlink, self._written_files)
            if getattr(self, '_remove_tempdir_on_clean', False):
                shutil.rmtree(self._tempdir)
519524
def unzip_file(zip_fname):
    """""" 
    print("Unzipping {}".format(zip_fname))
    with zipfile.ZipFile(zip_fname) as zf:
        zf.extractall()
596617
def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
    

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

    with zipfile.ZipFile(filename) as z:
        for info in z.infolist():
            name = info.filename

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

            target = os.path.join(extract_dir, *name.split('/'))
            target = progress_filter(name, target)
            if not target:
                continue
            if name.endswith('/'):
                # directory
                ensure_directory(target)
            else:
                # file
                ensure_directory(target)
                data = z.read(info.filename)
                with open(target, 'wb') as f:
                    f.write(data)
            unix_attributes = info.external_attr >> 16
            if unix_attributes:
                os.chmod(target, unix_attributes)
1173364
def unzip(filename, root, verbose=True):
  
  for message in _unzip_iter(filename, root, verbose):
    if isinstance(message, ErrorMessage):
      raise Exception(message)
1209484
private void unzip(final File file, final String outputDir) throws IOException {

		try (final ZipFile zipFile = new ZipFile(file)) {

			final Enumeration<? extends ZipEntry> entries = zipFile.entries();

			while (entries.hasMoreElements()) {

				final ZipEntry entry = entries.nextElement();
				final File targetFile = new File(outputDir, entry.getName());

				if (entry.isDirectory()) {

					targetFile.mkdirs();

				} else {

					targetFile.getParentFile().mkdirs();
					InputStream in = zipFile.getInputStream(entry);

					try (OutputStream out = new FileOutputStream(targetFile)) {

						IOUtils.copy(in, out);
						IOUtils.closeQuietly(in);
					}
				}
			}
		}
	}
798823
def _uncompress_file(self, path):
        '''
        
        '''

        with self.file.open('rb') as f:
            if (self.cdfversion == 3):
                data_start, data_size, cType, _ = self._read_ccr(8)
            else:
                data_start, data_size, cType, _ = self._read_ccr2(8)

            if cType != 5:
                return
            f.seek(data_start)
            decompressed_data = gzip.decompress(f.read(data_size))

        newpath = pathlib.Path(tempfile.NamedTemporaryFile(suffix='.cdf').name)
        with newpath.open('wb') as g:
            g.write(bytearray.fromhex('cdf30001'))
            g.write(bytearray.fromhex('0000ffff'))
            g.write(decompressed_data)

        return newpath
582443
def unzip_file_to_dir(path_to_zip, output_directory):
    
    z = ZipFile(path_to_zip, 'r')
    z.extractall(output_directory)
    z.close()
891515
def _prepare_temp_dir(self):
    """"""
    if not shell_call(['sudo', 'rm', '-rf', os.path.join(self._temp_dir, '*')]):
      logging.error('Failed to cleanup temporary directory.')
      sys.exit(1)
    # NOTE: we do not create self._extracted_submission_dir
    # this is intentional because self._tmp_extracted_dir or it's subdir
    # will be renames into self._extracted_submission_dir
    os.mkdir(self._tmp_extracted_dir)
    os.mkdir(self._sample_input_dir)
    os.mkdir(self._sample_output_dir)
    # make output dir world writable
    shell_call(['chmod', 'a+rwX', '-R', self._sample_output_dir])
1219086
def remove_temporary_source(self):
        """"""
        if self.is_bundle or os.path.exists(self.delete_marker_filename):
            logger.info('Removing source in %s' % self.source_dir)
            if self.source_dir:
                rmtree(self.source_dir)
            self.source_dir = None
        if self._temp_build_dir and os.path.exists(self._temp_build_dir):
            rmtree(self._temp_build_dir)
        self._temp_build_dir = None
670866
def unarchive(self, target_path=None, zip_path=None):
        
        if target_path:
            self.target_path = target_path

        if zip_path:
            self.zip_path = zip_path

        if self.has_path is False:
            raise RuntimeError("")

        if os.path.isdir(self.target_path) is False:
            os.mkdir(self.target_path)

        with zipfile.ZipFile(self.zip_path, 'r') as zip:
            zip.extractall(self.target_path)
75634
def unzip(self, overwrite: bool = False):
        

        if self.zip_content and not overwrite:
            raise FileExistsError(str(self.temp_dir))

        LOGGER.debug('unzipping miz to temp dir')

        try:

            with ZipFile(str(self.miz_path)) as zip_file:

                LOGGER.debug('reading infolist')

                self.zip_content = [f.filename for f in zip_file.infolist()]

                self._extract_files_from_zip(zip_file)

        except BadZipFile:
            raise BadZipFile(str(self.miz_path))

        except:  # noqa: E722
            LOGGER.exception('error while unzipping miz file: %s', self.miz_path)
            raise

        LOGGER.debug('checking miz content')

        # noinspection PyTypeChecker
        for miz_item in ['mission', 'options', 'warehouses', 'l10n/DEFAULT/dictionary', 'l10n/DEFAULT/mapResource']:
            if not Path(self.temp_dir.joinpath(miz_item)).exists():
                LOGGER.error('missing file in miz: %s', miz_item)
                raise FileNotFoundError(miz_item)

        self._check_extracted_content()

        LOGGER.debug('all files have been found, miz successfully unzipped')
104573
def CleanUp(self, path):
    """"""
    try:
      if os.path.exists(path):
        os.remove(path)
    except (OSError, IOError) as e:
      logging.info("Failed to remove temporary file %s. Err: %s", path, e)
371712
def temporary_directory():
    
    dir_name = tempfile.mkdtemp()
    yield dir_name
    if os.path.exists(dir_name):
        shutil.rmtree(dir_name)
1306020
def _pack(self, fname, encoding):
        
        (fd, tmpfile) = tempfile.mkstemp()
        os.close(fd)
        try:
            self.save(tmpfile, mode='abs', validate=False)
            document_loader, processobj, metadata, uri = load_cwl(tmpfile)
        finally:
            # cleanup tmpfile
            os.remove(tmpfile)

        with codecs.open(fname, 'wb', encoding=encoding) as f:
            f.write(print_pack(document_loader, processobj, uri, metadata))