Class: OpsWalrus::DirZipper

Inherits:
Object
  • Object
show all
Defined in:
lib/opswalrus/zip.rb

Class Method Summary collapse

Class Method Details

.unzip(input_file, output_dir) ⇒ Object

returns output_dir



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/opswalrus/zip.rb', line 19

def self.unzip(input_file, output_dir)
  if !File.exist?(output_dir) || File.directory?(output_dir)
    FileUtils.mkdir_p(output_dir)
    ::Zip::File.foreach(input_file) do |entry|
      path = File.join(output_dir, entry.name)
      entry.extract(path) unless File.exist?(path)
    end
  else
    raise Error, "#{output_dir} is not a directory"
  end

  output_dir
end

.write_entries(input_dir, entries, path, zipfile) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/opswalrus/zip.rb', line 33

def self.write_entries(input_dir, entries, path, zipfile)
  entries.each do |e|
    zipfile_path = path == '' ? e : File.join(path, e)
    disk_file_path = File.join(input_dir, zipfile_path)

    if File.directory?(disk_file_path)
      zipfile.mkdir(zipfile_path)
      subdir = Dir.entries(disk_file_path) - %w[. ..]
      write_entries(input_dir, subdir, zipfile_path, zipfile)
    else
      zipfile.add(zipfile_path, disk_file_path)
    end
  end
end

.zip(input_dir, output_file) ⇒ Object

Zip the input directory. returns output_file



8
9
10
11
12
13
14
15
16
# File 'lib/opswalrus/zip.rb', line 8

def self.zip(input_dir, output_file)
  entries = Dir.entries(input_dir) - %w[. ..]

  ::Zip::File.open(output_file, create: true) do |zipfile|
    write_entries(input_dir, entries, '', zipfile)
  end

  output_file
end