private static PreparedLayer compressAndCacheTarLayer(
      Cache cache,
      DescriptorDigest diffId,
      Path layerFile,
      boolean layersAreCompressed,
      ProgressEventDispatcher.Factory progressEventDispatcherFactory)
      throws IOException, CacheCorruptedException {
    try (ProgressEventDispatcher childDispatcher =
            progressEventDispatcherFactory.create(
                "compressing layer " + diffId, Files.size(layerFile));
        ThrottledAccumulatingConsumer throttledProgressReporter =
            new ThrottledAccumulatingConsumer(childDispatcher::dispatchProgress)) {
      // Retrieve pre-compressed layer from cache
      Optional<CachedLayer> optionalLayer = cache.retrieveTarLayer(diffId);
      if (optionalLayer.isPresent()) {
        return new PreparedLayer.Builder(optionalLayer.get()).build();
      }

      // Just write layers that are already compressed
      if (layersAreCompressed) {
        return new PreparedLayer.Builder(cache.writeTarLayer(diffId, Blobs.from(layerFile)))
            .build();
      }

      // Compress uncompressed layers while writing
      Blob compressedBlob =
          Blobs.from(
              outputStream -> {
                try (GZIPOutputStream compressorStream = new GZIPOutputStream(outputStream);
                    NotifyingOutputStream notifyingOutputStream =
                        new NotifyingOutputStream(compressorStream, throttledProgressReporter)) {
                  Blobs.from(layerFile).writeTo(notifyingOutputStream);
                }
              },
              true);
      return new PreparedLayer.Builder(cache.writeTarLayer(diffId, compressedBlob)).build();
    }
  }
Checks the first two bytes of a file to see if it has been gzipped.

@param path the file to check
@return {@code true} if the file is gzipped, {@code false} if not
@throws IOException if reading the file fails
@see <a href="http://www.zlib.org/rfc-gzip.html#file-format">GZIP file format</a>
jib-core/src/main/java/com/google/cloud/tools/jib/builder/steps/LocalBaseImageSteps.java