Class: Archive::Tar::Writer

Inherits:
Object
  • Object
show all
Includes:
Archive::Tar
Defined in:
lib/archive/tar/writer.rb

Constant Summary

Constants included from Archive::Tar

VERSION

Instance Method Summary collapse

Methods included from Archive::Tar

#join_path, #normalize_path, #solve_path

Constructor Details

#initialize(stream, options = {}) ⇒ Writer

Returns a new instance of Writer.



32
33
34
35
36
37
38
39
40
41
# File 'lib/archive/tar/writer.rb', line 32

def initialize(stream, options = {})
  options = {
    block_size: 2 ** 19,
    format: :gnu
  }.merge(options)
  
  @options = options
  @stream = stream
  @inodes = {}
end

Instance Method Details

#add_directory(dir, options = {}) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/archive/tar/writer.rb', line 79

def add_directory(dir, options = {})
  options = {
    full_path: false,
    recursive: true,
    archive_base: ""
  }.merge(options)
  
  real_base = dir
  archive_base = options[:archive_base]
  
  unless dir.is_a? Dir
    dir = Dir.open(dir)
  end
  
  #add_file(dir.path, archive_base)
  
  dir.each do |entry|
    if entry == "." || entry == ".."
      next
    end
    
    realpath = File.join(real_base, entry)
    real_archive_path = join_path(archive_base, entry)
    
    add_file(realpath, real_archive_path)
    
    if File::Stat.new(realpath).directory? && options[:recursive]
      new_options = options
      new_options[:archive_base] = real_archive_path
      
      add_directory(realpath, new_options)
    end
  end
end

#add_entry(header, content) ⇒ Object



43
44
45
46
47
48
# File 'lib/archive/tar/writer.rb', line 43

def add_entry(header, content)
  @atream.write(Archive::Tar::Format::pack_header(header))
  
  content = content[0, header.size].ljust(header.blocks * 512, "\0")
  @stream.write(content)
end

#add_file(file, path = nil) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/archive/tar/writer.rb', line 50

def add_file(file, path = nil)
  file = File.is_a?(File) ? file : File.new(file)
  path = path == nil ? file.path : path
  
  ino = File::Stat.new(file).ino
  stat = Archive::Tar::Stat::from_file(file)
  stat.path = path
  stat.format = @options[:format]
  if @inodes.has_key? ino && path != @inodes[ino]
    stat.type = :link
    stat.size = 0
    stat.dest = @inodes[ino]
  else
    @inodes[ino] = path
  end
  
  header = Archive::Tar::Format::pack_header(stat)
  @stream.write(header)
  
  if stat.type == :normal
    num_of_nils = stat.blocks * 512 - stat.size
    until file.eof?
      @stream.write(file.read(@options[:block_size]))
    end
    
    @stream.write("\0" * num_of_nils)
  end
end

#closeObject



114
115
116
# File 'lib/archive/tar/writer.rb', line 114

def close()
  @stream.write("\0" * 1024)
end