class Inspec::RelativeFileProvider

Constants

BLACKLIST_FILES

Attributes

files[R]
parent[R]
prefix[R]

Public Class Methods

new(parent_provider) click to toggle source
# File lib/inspec/file_provider.rb, line 229
def initialize(parent_provider)
  @parent = parent_provider
  @prefix = get_prefix(parent.files)
  if @prefix.nil?
    raise "Could not determine path prefix for #{parent}"
  end

  # select all files that begin with the prefix, and strip off the prefix from the file.
  #
  # strip off any leading top-level relative path (./) which is common in
  # PAX-formatted tar files. Do not do any translation of the path if the
  # path is an absolute path.
  @files = parent.files
    .find_all { |x| x.start_with?(prefix) && x != prefix }
    .map { |x| x[prefix.length..-1] }
    .map do |x|
      path = Pathname.new(x)
      path.absolute? ? path.to_s : path.relative_path_from(Pathname.new(".")).to_s
    end
end

Public Instance Methods

abs_path(file) click to toggle source
# File lib/inspec/file_provider.rb, line 250
def abs_path(file)
  return nil if file.nil?

  prefix + file
end
binread(file) click to toggle source
# File lib/inspec/file_provider.rb, line 260
def binread(file)
  parent.binread(abs_path(file))
end
read(file) click to toggle source
# File lib/inspec/file_provider.rb, line 256
def read(file)
  parent.read(abs_path(file))
end

Private Instance Methods

get_files_prefix(fs) click to toggle source
# File lib/inspec/file_provider.rb, line 297
def get_files_prefix(fs)
  return "" if fs.empty?

  file = fs[0]
  bn = File.basename(file)
  # no more prefixes
  return "" if bn == file

  i = file.rindex(bn)
  pre = file[0..i - 1]

  rest = fs.find_all { |f| !f.start_with?(pre) }
  return pre if rest.empty?

  new_pre = get_prefix(rest)
  return new_pre if pre.start_with? new_pre

  # edge case: completely different prefixes; retry prefix detection
  a = File.dirname(pre + "a")
  b = File.dirname(new_pre + "b")
  get_prefix([a, b])
end
get_folder_prefix(fs) click to toggle source
# File lib/inspec/file_provider.rb, line 284
def get_folder_prefix(fs)
  return get_files_prefix(fs) if fs.length == 1

  first, *rest = fs
  pre = prefix_candidate_for(first)

  if rest.all? { |i| i.start_with? pre }
    return get_folder_prefix(rest)
  end

  get_files_prefix(fs)
end
get_prefix(fs) click to toggle source
# File lib/inspec/file_provider.rb, line 266
def get_prefix(fs)
  return "" if fs.empty?

  # filter backlisted files
  fs -= BLACKLIST_FILES

  sorted = fs.sort_by(&:length)
  get_folder_prefix(sorted)
end
prefix_candidate_for(file) click to toggle source
# File lib/inspec/file_provider.rb, line 276
def prefix_candidate_for(file)
  if file.end_with?(File::SEPARATOR)
    file
  else
    file + File::SEPARATOR
  end
end