Sha256: 98deb8aa7d35a15dbbbff885e7f3615eb8c08ff5c0e0ea22f31463212a41c1b1

Contents?: true

Size: 1.45 KB

Versions: 4

Compression:

Stored size: 1.45 KB

Contents

require "metacrunch/file"
require "rubygems/package"

module Metacrunch
  class File::FileSource

    def initialize(filenames)
      @filenames = [*filenames].map{|f| f.presence}.compact
    end

    def each(&block)
      return enum_for(__method__) unless block_given?

      @filenames.each do |filename|
        if is_archive?(filename)
         read_archive(filename, &block)
        else
         read_regular_file(filename, &block)
        end
      end
    end

  private

    def is_archive?(filename)
      filename.ends_with?(".tar") || filename.ends_with?(".tar.gz") || filename.ends_with?(".tgz")
    end

    def is_gzip_file?(filename)
      filename.ends_with?(".gz") || filename.ends_with?(".tgz")
    end

    def read_regular_file(filename, &block)
      if ::File.file?(filename)
        io = is_gzip_file?(filename) ? Zlib::GzipReader.open(filename) : ::File.open(filename, "r")
        yield File::Entry.new(filename: filename, archive_filename: nil, contents: io.read)
      end
    end

    def read_archive(filename, &block)
      io        = is_gzip_file?(filename) ? Zlib::GzipReader.open(filename) : ::File.open(filename, "r")
      tarReader = Gem::Package::TarReader.new(io)

      tarReader.each do |_tar_entry|
        if _tar_entry.file?
          yield File::Entry.new(
            filename: filename,
            archive_filename: _tar_entry.full_name,
            contents: _tar_entry.read
          )
        end
      end
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
metacrunch-file-1.5.0 lib/metacrunch/file/file_source.rb
metacrunch-file-1.4.0 lib/metacrunch/file/file_source.rb
metacrunch-file-1.3.1 lib/metacrunch/file/file_source.rb
metacrunch-file-1.3.0 lib/metacrunch/file/file_source.rb