Module: Unpacker

Defined in:
lib/unpacker.rb

Defined Under Namespace

Classes: UnrecognizedArchiveError

Constant Summary collapse

SUPPORTED_FILEEXTS =
%w[tar rar zip gz bz tgz bgz tar]

Class Method Summary collapse

Class Method Details

.archive?(file_name) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/unpacker.rb', line 56

def self.archive?(file_name)
  SUPPORTED_FILEEXTS.include? File.extname(file_name).sub('.', '')
end

.unpack(file, tmpdir = "/tmp", &block) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/unpacker.rb', line 34

def self.unpack(file, tmpdir = "/tmp", &block)
  Dir.mktmpdir 'unpacker' do |dir|
    cmd = case file
          when /rar$/
            "unrar x -y #{file} #{dir}"
          when /(tar|tgz|tar\.gz|tar\.bz|tbz)$/
            "tar xvf #{file} --directory #{dir}"
          when /zip$/
            "unzip #{file} -d #{dir}"
          when /gz$/
            "gunzip -c #{file} #{File.join(dir, "gz-contents")}"
          else
            raise UnrecognizedArchiveError
          end
    stdout, stderr, status = Open3.capture3 cmd
    if !status.success?
      raise RuntimeError.new("There was a problem unpacking #{file}\n#{stderr}")
    end
    block.call Dir.new(dir)
  end
end

.valid?(file_path, file_name = file_path) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/unpacker.rb', line 60

def self.valid?(file_path, file_name = file_path)
  cmd = case file_name
        when /rar$/
          "unrar t #{file_path}"
        when /(tar|tar\.bz|tbz)$/
          "tar tf #{file_path}"
        when /zip$/
          "zip -T #{file_path}"
        when /gz|tgz$/
          "gunzip -t #{file_path}"
        else
          raise UnrecognizedArchiveError
        end
  `#{cmd}`
  true
rescue
  false
end