class Inspec::TarProvider

Attributes

files[R]

Public Class Methods

new(path) click to toggle source
# File lib/inspec/file_provider.rb, line 159
def initialize(path)
  @path = path
  @contents = {}

  here = Pathname.new(".")

  walk_tar(@path) do |entries|
    entries.each do |entry|
      name = entry.full_name

      # rubocop:disable Layout/MultilineOperationIndentation
      # rubocop:disable Style/ParenthesesAroundCondition
      next unless (entry.file? &&              # duh
                   !name.empty? &&             # for empty filenames?
                   name !~ %r{\.\.(?:/|\z)} && # .. (to avoid attacks?)
                   !name.include?("PaxHeader/"))

      path = Pathname.new(name).relative_path_from(here).to_s

      @contents[path] = begin # not ||= in a tarball, last one wins
                          res = entry.read || ""
                          try = res.dup
                          try.force_encoding Encoding::UTF_8
                          res = try.encode(try.encoding, universal_newline: true) if
                            try.valid_encoding?
                          res
                        end
    end

    @files = @contents.keys
  end
end

Public Instance Methods

extract(destination_path = ".") click to toggle source
# File lib/inspec/file_provider.rb, line 192
def extract(destination_path = ".")
  FileUtils.mkdir_p(destination_path)

  @contents.each do |path, body|
    full_path = File.join(destination_path, path)

    FileUtils.mkdir_p(File.dirname(full_path))
    File.open(full_path, "wb") { |f| f.write(body) }
  end
end
read(file) click to toggle source
# File lib/inspec/file_provider.rb, line 203
def read(file)
  @contents[file]
end

Private Instance Methods

walk_tar(path, &callback) click to toggle source
# File lib/inspec/file_provider.rb, line 209
def walk_tar(path, &callback)
  tar_file = Zlib::GzipReader.open(path)
  Gem::Package::TarReader.new(tar_file, &callback)
rescue => e
  raise Inspec::Error, "Error opening/processing #{path}: #{e.message}"
ensure
  tar_file.close if tar_file
end