class Inspec::ZipProvider

Attributes

files[R]

Public Class Methods

new(path) click to toggle source
# File lib/inspec/file_provider.rb, line 97
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

Public Instance Methods

extract(destination_path = ".") click to toggle source
# File lib/inspec/file_provider.rb, line 109
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
read(file) click to toggle source
# File lib/inspec/file_provider.rb, line 125
def read(file)
  # TODO: this is inefficient
  @contents[file] ||= read_from_zip(file)
end

Private Instance Methods

read_from_zip(file) click to toggle source
# File lib/inspec/file_provider.rb, line 136
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
walk_zip(path, &callback) click to toggle source
# File lib/inspec/file_provider.rb, line 132
def walk_zip(path, &callback)
  ::Zip::InputStream.open(path, &callback)
end