class Inspec::ZipProvider

def extract(destination_path = ".")

def extract(destination_path = ".")
  FileUtils.mkdir_p(destination_path)
  Zip::File.open(@path) do |archive|
    archive.each do |file|
      final_path = File.join(destination_path, file.name)
      # This removes the top level directory (and any other files) to ensure
      # extracted files do not conflict.
      FileUtils.remove_entry(final_path) if File.exist?(final_path)
      archive.extract(file, final_path)
    end
  end
end

def initialize(path)

def initialize(path)
  @path = path
  @contents = {}
  @files = []
  walk_zip(@path) do |io|
    while (entry = io.get_next_entry)
      name = entry.name.sub(%r{/+$}, "")
      @files.push(name) unless name.empty? || name.squeeze("/") =~ %r{\.{2}(?:/|\z)}
    end
  end
end

def read(file)

def read(file)
  # TODO: this is inefficient
  @contents[file] ||= read_from_zip(file)
end

def read_from_zip(file)

def read_from_zip(file)
  return nil unless @files.include?(file)
  res = nil
  walk_zip(@path) do |io|
    while (entry = io.get_next_entry)
      next unless file == entry.name
      res = io.read
      try = res.dup
      try.force_encoding Encoding::UTF_8
      res = try.encode(try.encoding, universal_newline: true) if try.valid_encoding?
      break
    end
  end
  res
end

def walk_zip(path, &callback)

def walk_zip(path, &callback)
  ::Zip::InputStream.open(path, &callback)
end