Compress a file returning the new filename (.gz)
492873
def __gzip(filename):
		
		zipname = filename + '.gz'
		file_pointer = open(filename,'rb')
		zip_pointer = gzip.open(zipname,'wb')
		zip_pointer.writelines(file_pointer)
		file_pointer.close()
		zip_pointer.close()
		return zipname
148565
def uncompressed_size(filename):
    

    quoted_filename = shlex.quote(filename)

    # TODO: get filetype from file-magic, if available
    if str(filename).lower().endswith(".xz"):
        output = execute_command('xz --list "{}"'.format(quoted_filename))
        compressed, uncompressed = regexp_sizes.findall(output)
        value, unit = uncompressed.split()
        value = float(value.replace(",", ""))
        return int(value * MULTIPLIERS[unit])

    elif str(filename).lower().endswith(".gz"):
        # XXX: gzip only uses 32 bits to store uncompressed size, so if the
        # uncompressed size is greater than 4GiB, the value returned will be
        # incorrect.
        output = execute_command('gzip --list "{}"'.format(quoted_filename))
        lines = [line.split() for line in output.splitlines()]
        header, data = lines[0], lines[1]
        gzip_data = dict(zip(header, data))
        return int(gzip_data["uncompressed"])

    else:
        raise ValueError('Unrecognized file type for "{}".'.format(filename))
96260
def open_compressed(filename, mode="r", encoding=None):
    ""

    # TODO: integrate this function in the library itself, using
    # get_filename_and_fobj
    binary_mode = "b" in mode
    extension = str(filename).split(".")[-1].lower()
    if binary_mode and encoding:
        raise ValueError("encoding should not be specified in binary mode")

    if extension == "xz":
        if lzma is None:
            raise RuntimeError("lzma support is not installed")

        fobj = lzma.open(filename, mode=mode)
        if binary_mode:
            return fobj
        else:
            return io.TextIOWrapper(fobj, encoding=encoding)

    elif extension == "gz":
        fobj = gzip.GzipFile(filename, mode=mode)
        if binary_mode:
            return fobj
        else:
            return io.TextIOWrapper(fobj, encoding=encoding)

    elif extension == "bz2":
        if bz2 is None:
            raise RuntimeError("bzip2 support is not installed")

        if binary_mode:  # ignore encoding
            return bz2.open(filename, mode=mode)
        else:
            if "t" not in mode:
                # For some reason, passing only mode='r' to bzip2 is equivalent
                # to 'rb', not 'rt', so we force it here.
                mode += "t"
            return bz2.open(filename, mode=mode, encoding=encoding)

    else:
        if binary_mode:
            return open(filename, mode=mode)
        else:
            return open(filename, mode=mode, encoding=encoding)
897611
def __unpack_tgz(self, filename):
        """"""
        if isinstance(filename, string_types) and self.__isValidTGZ(filename) and tarfile.is_tarfile(filename):
            with tarfile.open(filename, mode='r:gz') as t:
                for name in t.getnames():
                    t.extract(name, self.plugin_abspath)
        else:
            raise TarError("Invalid Plugin Compressed File")
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
53980
def _gzip_open_filename(handle):
    """"""
    import gzip
    if sys.version_info[0] > 2:
        handle = gzip.open(handle, mode='rt', encoding="UTF-8")
    else:
        handle = gzip.open(handle)
    return handle
892930
function _minFile(rawFile, compressedFile) {
    if (compressedFile.size < rawFile.size) {
        return qfs.move(compressedFile.name, rawFile.name)
            .then(function () {
                return new File(rawFile.name, compressedFile.size);
            });
    }

    return compressedFile.remove()
        .then(function () {
            return rawFile;
        });
}
528169
def bin_open(fname: str):
    
    if fname.endswith(".gz"):
        return gzip.open(fname, "rb")
    return open(fname, "rb")
629670
def gzip(self, data, truncate=True):
        '''
        
        '''
        # Entropy is a simple ratio of: <zlib compressed size> / <original
        # size>
        e = float(float(len(zlib.compress(str2bytes(data), 9))) / float(len(data)))

        if truncate and e > 1.0:
            e = 1.0

        return e
913844
def fwriter(filename, gz=False, bz=False):
    

    if filename.endswith('.gz'):
        gz = True
    elif filename.endswith('.bz2'):
        bz = True

    if gz:
        if not filename.endswith('.gz'):
            filename += '.gz'
        return gzip.open(filename, 'wb')
    elif bz:
        if not filename.endswith('.bz2'):
            filename += '.bz2'
        return bz2.BZ2File(filename, 'w')
    else:
        return open(filename, 'w')
1008869
def compress(self, image_path):
    ''''''
    if os.path.exists(image_path):
        compressed_image = "%s.gz" %image_path
        os.system('gzip -c -6 %s > %s' %(image_path, compressed_image))
        return compressed_image

    bot.exit("Cannot find image %s" %image_path)
738914
public static void compressTGZ(Resource[] sources, Resource target, int mode) throws IOException {
	File tmpTarget = File.createTempFile("_temp", "tmp");
	try {
	    // write Tar
	    OutputStream tmpOs = new FileOutputStream(tmpTarget);
	    try {
		compressTar(sources, tmpOs, mode);
	    }
	    finally {
		IOUtil.closeEL(tmpOs);
	    }

	    // write Gzip
	    InputStream is = null;
	    OutputStream os = null;
	    try {
		is = new FileInputStream(tmpTarget);
		os = target.getOutputStream();
		compressGZip(is, os);
	    }
	    finally {
		IOUtil.closeEL(is, os);
	    }
	}
	finally {
	    tmpTarget.delete();
	}
    }
1268577
def _expand_filename(self, line):
        """"""
        # expand .
        newline = line
        path = os.getcwd()
        if newline.startswith("."):
            newline = newline.replace(".", path, 1)
        # expand ~
        newline = os.path.expanduser(newline)
        return newline
725083
def unzip_file_if_necessary(self, source_file):
        
        if source_file.endswith(".gz"):
            self.print_message("Decompressing '%s'" % source_file)
            subprocess.check_call(["gunzip", "--force", source_file])
            source_file = source_file[:-len(".gz")]
        return source_file
414035
def open_as_needed(filename):
    
    if hasattr(filename, 'read'):
        return filename

    if filename.endswith('.bz2'):
        return bz2.BZ2File(filename, 'rb')
    elif filename.endswith('.gz'):
        return gzip.GzipFile(filename, 'rb')
    else:
        return open(filename, 'rb')
1220921
public static InputStream decompress(final InputStream in, final String fileName) throws IOException
  {
    if (fileName.endsWith(GZ_SUFFIX)) {
      return gzipInputStream(in);
    } else if (fileName.endsWith(BZ2_SUFFIX)) {
      return new BZip2CompressorInputStream(in, true);
    } else if (fileName.endsWith(XZ_SUFFIX)) {
      return new XZCompressorInputStream(in, true);
    } else if (fileName.endsWith(SNAPPY_SUFFIX)) {
      return new FramedSnappyCompressorInputStream(in);
    } else if (fileName.endsWith(ZSTD_SUFFIX)) {
      return new ZstdCompressorInputStream(in);
    } else if (fileName.endsWith(ZIP_SUFFIX)) {
      // This reads the first file in the archive.
      final ZipInputStream zipIn = new ZipInputStream(in, StandardCharsets.UTF_8);
      try {
        final ZipEntry nextEntry = zipIn.getNextEntry();
        if (nextEntry == null) {
          zipIn.close();

          // No files in the archive - return an empty stream.
          return new ByteArrayInputStream(new byte[0]);
        }
        return zipIn;
      }
      catch (IOException e) {
        try {
          zipIn.close();
        }
        catch (IOException e2) {
          e.addSuppressed(e2);
        }
        throw e;
      }
    } else {
      return in;
    }
  }
515451
def compress_directory(dir)
      File.open archive_path(dir), 'wb' do |oarchive_path|
        Zlib::GzipWriter.wrap oarchive_path do |gz|
          Gem::Package::TarWriter.new gz do |tar|
            Find.find "#{builds_dir}/"+dir do |f|
              relative_path = f.sub "#{builds_dir}/", ""
              mode = File.stat(f).mode
              size = File.stat(f).size
              
              if File.directory? f
                tar.mkdir relative_path, mode
              else
                tar.add_file_simple relative_path, mode, size do |tio|
                  File.open f, 'rb' do |rio|
                    while buffer = rio.read(BLOCKSIZE_TO_READ)
                      tio.write buffer
                    end
                  end
                end
              end
              
            end
          end
        end
      end
      
    end