Module: DTK::Network::Client::Util::Tar

Included in:
Command, Command::Install, ModuleDir
Defined in:
lib/client/util/tar.rb

Instance Method Summary collapse

Instance Method Details

#gzip(tarfile) ⇒ Object

gzips the underlying string in the given StringIO, returning a new StringIO representing the compressed file.



63
64
65
66
67
68
69
70
71
72
# File 'lib/client/util/tar.rb', line 63

def gzip(tarfile)
  gz = StringIO.new("")
  z = Zlib::GzipWriter.new(gz)
  z.write tarfile.string
  z.close # this is necessary!

  # z was closed to write the gzip footer, so
  # now we need a new StringIO
  StringIO.new gz.string
end

#tar(path, opts = {}) ⇒ Object

Creates a tar file in memory recursively from the given path.

Returns a StringIO whose underlying String is the contents of the tar file.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/client/util/tar.rb', line 36

def tar(path, opts = {})
  tarfile = StringIO.new("")
  Gem::Package::TarWriter.new(tarfile) do |tar|
    nested_content = Dir.glob(File.join(path, "**/*"), File::FNM_DOTMATCH)
    nested_content.reject!{ |f_name| f_name.include?('.git')} if opts[:exclude_git]

    nested_content.each do |file|
      mode = File.stat(file).mode
      relative_file = file.sub /^#{Regexp::escape path}\/?/, ''

      if File.directory?(file)
        tar.mkdir relative_file, mode
      else
        tar.add_file relative_file, mode do |tf|
          File.open(file, "rb") { |f| tf.write f.read }
        end
      end
    end
  end

  tarfile.rewind
  tarfile
end

#ungzip(tarfile) ⇒ Object

un-gzips the given IO, returning the decompressed version as a StringIO



76
77
78
79
80
81
# File 'lib/client/util/tar.rb', line 76

def ungzip(tarfile)
  z = Zlib::GzipReader.new(tarfile)
  unzipped = StringIO.new(z.read)
  z.close
  unzipped
end

#untar(io, destination) ⇒ Object

untars the given IO into the specified directory



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/client/util/tar.rb', line 85

def untar(io, destination)
  Gem::Package::TarReader.new io do |tar|
    tar.each do |tarfile|
      destination_file = File.join destination, tarfile.full_name
      
      if tarfile.directory?
        FileUtils.mkdir_p destination_file
      else
        destination_directory = File.dirname(destination_file)
        FileUtils.mkdir_p destination_directory unless File.directory?(destination_directory)
        File.open destination_file, "wb" do |f|
          f.print tarfile.read
        end
      end
    end
  end
end