Class: Zip::File
- Inherits:
-
CentralDirectory
- Object
- CentralDirectory
- Zip::File
- Includes:
- FileSystem
- Defined in:
- lib/zip/file.rb,
lib/zip/filesystem.rb
Overview
ZipFile is modeled after java.util.zip.ZipFile from the Java SDK. The most important methods are those inherited from ZipCentralDirectory for accessing information about the entries in the archive and methods such as get_input_stream and get_output_stream for reading from and writing entries to the archive. The class includes a few convenience methods such as #extract for extracting entries to the filesystem, and #remove, #replace, #rename and #mkdir for making simple modifications to the archive.
Modifications to a zip archive are not committed until #commit or #close is called. The method #open accepts a block following the pattern from File.open offering a simple way to automatically close the archive when the block returns.
The following example opens zip archive my.zip
(creating it if it doesn’t exist) and adds an entry first.txt
and a directory entry a_dir
to it.
require 'zip'
Zip::File.open("my.zip", Zip::File::CREATE) {
|zipfile|
zipfile.get_output_stream("first.txt") { |f| f.puts "Hello from ZipFile" }
zipfile.mkdir("a_dir")
}
The next example reopens my.zip
writes the contents of first.txt
to standard out and deletes the entry from the archive.
require 'zip'
Zip::File.open("my.zip", Zip::File::CREATE) {
|zipfile|
puts zipfile.read("first.txt")
zipfile.remove("first.txt")
}
ZipFileSystem offers an alternative API that emulates ruby’s interface for accessing the filesystem, ie. the File and Dir classes.
Constant Summary collapse
- CREATE =
1
- SPLIT_SIGNATURE =
0x08074b50
- ZIP64_EOCD_SIGNATURE =
0x06064b50
- MAX_SEGMENT_SIZE =
3221225472
- MIN_SEGMENT_SIZE =
65536
- DATA_BUFFER_SIZE =
8192
Constants inherited from CentralDirectory
CentralDirectory::END_OF_CDS, CentralDirectory::MAX_END_OF_CDS_SIZE, CentralDirectory::STATIC_EOCD_SIZE, CentralDirectory::ZIP64_END_OF_CDS, CentralDirectory::ZIP64_EOCD_LOCATOR
Instance Attribute Summary collapse
-
#comment ⇒ Object
Returns the zip files comment, if it has one.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#restore_ownership ⇒ Object
default -> false.
-
#restore_permissions ⇒ Object
default -> false.
-
#restore_times ⇒ Object
default -> true.
Class Method Summary collapse
-
.add_buffer {|zf| ... } ⇒ Object
Same as #open.
-
.foreach(aZipFileName, &block) ⇒ Object
Iterates over the contents of the ZipFile.
- .get_partial_zip_file_name(zip_file_name, partial_zip_file_name) ⇒ Object
- .get_segment_count_for_split(zip_file_size, segment_size) ⇒ Object
- .get_segment_size_for_split(segment_size) ⇒ Object
-
.open(file_name, create = nil) ⇒ Object
Same as #new.
-
.open_buffer(io, options = {}) {|zf| ... } ⇒ Object
Like #open, but reads zip archive contents from a String or open IO stream, and outputs data to a buffer.
- .put_split_signature(szip_file, segment_size) ⇒ Object
-
.save_splited_part(zip_file, partial_zip_file_name, zip_file_size, szip_file_index, segment_size, segment_count) ⇒ Object
TODO: Make the code more understandable.
-
.split(zip_file_name, segment_size = MAX_SEGMENT_SIZE, delete_zip_file = true, partial_zip_file_name = nil) ⇒ Object
Splits an archive into parts with segment size.
Instance Method Summary collapse
-
#add(entry, srcPath, &continue_on_exists_proc) ⇒ Object
Convenience method for adding the contents of a file to the archive.
-
#close ⇒ Object
Closes the zip file committing any changes that has been made.
-
#commit ⇒ Object
Commits changes that has been made since the previous commit to the zip archive.
-
#commit_required? ⇒ Boolean
Returns true if any changes has been made to this archive since the previous commit.
-
#extract(entry, dest_path, &block) ⇒ Object
Extracts entry to file dest_path.
-
#find_entry(entry_name) ⇒ Object
Searches for entry with the specified name.
-
#get_entry(entry) ⇒ Object
Searches for an entry just as find_entry, but throws Errno::ENOENT if no entry is found.
-
#get_input_stream(entry, &aProc) ⇒ Object
Returns an input stream to the specified entry.
-
#get_output_stream(entry, permissionInt = nil, comment = nil, extra = nil, compressed_size = nil, crc = nil, compression_method = nil, size = nil, time = nil, &aProc) ⇒ Object
Returns an output stream to the specified entry.
-
#glob(*args, &block) ⇒ Object
Searches for entries given a glob.
-
#initialize(file_name, create = nil, buffer = false, options = {}) ⇒ File
constructor
Opens a zip archive.
-
#mkdir(entryName, permissionInt = 0755) ⇒ Object
Creates a directory.
-
#read(entry) ⇒ Object
Returns a string containing the contents of the specified entry.
-
#remove(entry) ⇒ Object
Removes the specified entry.
-
#rename(entry, new_name, &continue_on_exists_proc) ⇒ Object
Renames the specified entry.
-
#replace(entry, srcPath) ⇒ Object
Replaces the specified entry with the contents of srcPath (from the file system).
-
#to_s ⇒ Object
Returns the name of the zip archive.
-
#write_buffer ⇒ Object
Write buffer write changes to buffer and return.
Methods included from FileSystem
Methods inherited from CentralDirectory
#==, #each, #entries, #get_64_e_o_c_d, #get_e_o_c_d, #read_64_e_o_c_d, #read_central_directory_entries, #read_e_o_c_d, #read_from_stream, read_from_stream, #size, #start_buf, #write_to_stream, #zip64_file?
Constructor Details
#initialize(file_name, create = nil, buffer = false, options = {}) ⇒ File
Opens a zip archive. Pass true as the second parameter to create a new archive if it doesn’t exist already.
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/zip/file.rb', line 67 def initialize(file_name, create = nil, buffer = false, = {}) super() @name = file_name @comment = '' @create = create case when ::File.exists?(file_name) && !buffer @create = nil @exist_file_perms = ::File.stat(file_name).mode ::File.open(name, 'rb') do |f| read_from_stream(f) end when create @entry_set = EntrySet.new else raise ZipError, "File #{file_name} not found" end @stored_entries = @entry_set.dup @stored_comment = @comment @restore_ownership = [:restore_ownership] || false @restore_permissions = [:restore_permissions] || true @restore_times = [:restore_times] || true end |
Instance Attribute Details
#comment ⇒ Object
Returns the zip files comment, if it has one
63 64 65 |
# File 'lib/zip/file.rb', line 63 def comment @comment end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
54 55 56 |
# File 'lib/zip/file.rb', line 54 def name @name end |
#restore_ownership ⇒ Object
default -> false
57 58 59 |
# File 'lib/zip/file.rb', line 57 def restore_ownership @restore_ownership end |
#restore_permissions ⇒ Object
default -> false
59 60 61 |
# File 'lib/zip/file.rb', line 59 def @restore_permissions end |
#restore_times ⇒ Object
default -> true
61 62 63 |
# File 'lib/zip/file.rb', line 61 def restore_times @restore_times end |
Class Method Details
.add_buffer {|zf| ... } ⇒ Object
Same as #open. But outputs data to a buffer instead of a file
109 110 111 112 113 |
# File 'lib/zip/file.rb', line 109 def add_buffer zf = ::Zip::File.new('', true, true) yield zf zf.write_buffer end |
.foreach(aZipFileName, &block) ⇒ Object
Iterates over the contents of the ZipFile. This is more efficient than using a ZipInputStream since this methods simply iterates through the entries in the central directory structure in the archive whereas ZipInputStream jumps through the entire archive accessing the local entry headers (which contain the same information as the central directory).
139 140 141 142 143 |
# File 'lib/zip/file.rb', line 139 def foreach(aZipFileName, &block) open(aZipFileName) do |zipFile| zipFile.each(&block) end end |
.get_partial_zip_file_name(zip_file_name, partial_zip_file_name) ⇒ Object
156 157 158 159 160 161 |
# File 'lib/zip/file.rb', line 156 def get_partial_zip_file_name(zip_file_name, partial_zip_file_name) partial_zip_file_name = zip_file_name.sub(/#{::File.basename(zip_file_name)}\z/, partial_zip_file_name + ::File.extname(zip_file_name)) unless partial_zip_file_name.nil? partial_zip_file_name ||= zip_file_name partial_zip_file_name end |
.get_segment_count_for_split(zip_file_size, segment_size) ⇒ Object
163 164 165 |
# File 'lib/zip/file.rb', line 163 def get_segment_count_for_split(zip_file_size, segment_size) (zip_file_size / segment_size).to_i + (zip_file_size % segment_size == 0 ? 0 : 1) end |
.get_segment_size_for_split(segment_size) ⇒ Object
145 146 147 148 149 150 151 152 153 154 |
# File 'lib/zip/file.rb', line 145 def get_segment_size_for_split(segment_size) case when MIN_SEGMENT_SIZE > segment_size MIN_SEGMENT_SIZE when MAX_SEGMENT_SIZE < segment_size MAX_SEGMENT_SIZE else segment_size end end |
.open(file_name, create = nil) ⇒ Object
Same as #new. If a block is passed the ZipFile object is passed to the block and is automatically closed afterwards just as with ruby’s builtin File.open method.
95 96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/zip/file.rb', line 95 def open(file_name, create = nil) zf = ::Zip::File.new(file_name, create) if block_given? begin yield zf ensure zf.close end else zf end end |
.open_buffer(io, options = {}) {|zf| ... } ⇒ Object
Like #open, but reads zip archive contents from a String or open IO stream, and outputs data to a buffer. (This can be used to extract data from a downloaded zip archive without first saving it to disk.)
119 120 121 122 123 124 125 126 127 128 129 130 131 |
# File 'lib/zip/file.rb', line 119 def open_buffer(io, = {}) unless io.is_a?(IO) || io.is_a?(String) raise "Zip::File.open_buffer expects an argument of class String or IO. Found: #{io.class}" end zf = ::Zip::File.new('', true, true, ) if io.is_a?(::String) require 'stringio' io = ::StringIO.new(io) end zf.read_from_stream(io) yield zf zf.write_buffer end |
.put_split_signature(szip_file, segment_size) ⇒ Object
167 168 169 170 171 |
# File 'lib/zip/file.rb', line 167 def put_split_signature(szip_file, segment_size) signature_packed = [SPLIT_SIGNATURE].pack('V') szip_file << signature_packed segment_size - signature_packed.size end |
.save_splited_part(zip_file, partial_zip_file_name, zip_file_size, szip_file_index, segment_size, segment_count) ⇒ Object
TODO: Make the code more understandable
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
# File 'lib/zip/file.rb', line 176 def save_splited_part(zip_file, partial_zip_file_name, zip_file_size, szip_file_index, segment_size, segment_count) ssegment_size = zip_file_size - zip_file.pos ssegment_size = segment_size if ssegment_size > segment_size szip_file_name = "#{partial_zip_file_name}.#{'%03d'%(szip_file_index)}" ::File.open(szip_file_name, 'wb') do |szip_file| if szip_file_index == 1 ssegment_size = put_split_signature(szip_file, segment_size) end chunk_bytes = 0 until ssegment_size == chunk_bytes || zip_file.eof? segment_bytes_left = ssegment_size - chunk_bytes buffer_size = segment_bytes_left < DATA_BUFFER_SIZE ? segment_bytes_left : DATA_BUFFER_SIZE chunk = zip_file.read(buffer_size) chunk_bytes += buffer_size szip_file << chunk # Info for track splitting yield segment_count, szip_file_index, chunk_bytes, ssegment_size if block_given? end end end |
.split(zip_file_name, segment_size = MAX_SEGMENT_SIZE, delete_zip_file = true, partial_zip_file_name = nil) ⇒ Object
Splits an archive into parts with segment size
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
# File 'lib/zip/file.rb', line 198 def split(zip_file_name, segment_size = MAX_SEGMENT_SIZE, delete_zip_file = true, partial_zip_file_name = nil) raise ZipError, "File #{zip_file_name} not found" unless ::File.exists?(zip_file_name) raise Errno::ENOENT, zip_file_name unless ::File.readable?(zip_file_name) zip_file_size = ::File.size(zip_file_name) segment_size = get_segment_size_for_split(segment_size) return if zip_file_size <= segment_size segment_count = get_segment_count_for_split(zip_file_size, segment_size) # Checking for correct zip structure self.open(zip_file_name) {} partial_zip_file_name = get_partial_zip_file_name(zip_file_name, partial_zip_file_name) szip_file_index = 0 ::File.open(zip_file_name, 'rb') do |zip_file| until zip_file.eof? szip_file_index += 1 save_splited_part(zip_file, partial_zip_file_name, zip_file_size, szip_file_index, segment_size, segment_count) end end ::File.delete(zip_file_name) if delete_zip_file szip_file_index end |
Instance Method Details
#add(entry, srcPath, &continue_on_exists_proc) ⇒ Object
Convenience method for adding the contents of a file to the archive
261 262 263 264 265 266 267 |
# File 'lib/zip/file.rb', line 261 def add(entry, srcPath, &continue_on_exists_proc) continue_on_exists_proc ||= proc { Zip.continue_on_exists_proc } check_entry_exists(entry, continue_on_exists_proc, "add") newEntry = entry.kind_of?(Entry) ? entry : Entry.new(@name, entry.to_s) newEntry.gather_fileinfo_from_srcpath(srcPath) @entry_set << newEntry end |
#close ⇒ Object
Closes the zip file committing any changes that has been made.
324 325 326 |
# File 'lib/zip/file.rb', line 324 def close commit end |
#commit ⇒ Object
Commits changes that has been made since the previous commit to the zip archive.
300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
# File 'lib/zip/file.rb', line 300 def commit return if !commit_required? on_success_replace do |tmpFile| ::Zip::OutputStream.open(tmpFile) do |zos| @entry_set.each do |e| e.write_to_zip_output_stream(zos) e.dirty = false end zos.comment = comment end true end initialize(name) end |
#commit_required? ⇒ Boolean
Returns true if any changes has been made to this archive since the previous commit
330 331 332 333 334 335 |
# File 'lib/zip/file.rb', line 330 def commit_required? @entry_set.each do |e| return true if e.dirty end @comment != @stored_comment || @entry_set != @stored_entries || @create == File::CREATE end |
#extract(entry, dest_path, &block) ⇒ Object
Extracts entry to file dest_path.
292 293 294 295 296 |
# File 'lib/zip/file.rb', line 292 def extract(entry, dest_path, &block) block ||= proc { ::Zip.on_exists_proc } found_entry = get_entry(entry) found_entry.extract(dest_path, &block) end |
#find_entry(entry_name) ⇒ Object
Searches for entry with the specified name. Returns nil if no entry is found. See also get_entry
339 340 341 |
# File 'lib/zip/file.rb', line 339 def find_entry(entry_name) @entry_set.find_entry(entry_name) end |
#get_entry(entry) ⇒ Object
Searches for an entry just as find_entry, but throws Errno::ENOENT if no entry is found.
350 351 352 353 354 355 356 357 358 359 |
# File 'lib/zip/file.rb', line 350 def get_entry(entry) selected_entry = find_entry(entry) unless selected_entry raise Errno::ENOENT, entry end selected_entry.restore_ownership = @restore_ownership selected_entry. = @restore_permissions selected_entry.restore_times = @restore_times selected_entry end |
#get_input_stream(entry, &aProc) ⇒ Object
Returns an input stream to the specified entry. If a block is passed the stream object is passed to the block and the stream is automatically closed afterwards just as with ruby’s builtin File.open method.
224 225 226 |
# File 'lib/zip/file.rb', line 224 def get_input_stream(entry, &aProc) get_entry(entry).get_input_stream(&aProc) end |
#get_output_stream(entry, permissionInt = nil, comment = nil, extra = nil, compressed_size = nil, crc = nil, compression_method = nil, size = nil, time = nil, &aProc) ⇒ Object
Returns an output stream to the specified entry. If entry is not an instance of Zip::Entry, a new Zip::Entry will be initialized using the arguments specified. If a block is passed the stream object is passed to the block and the stream is automatically closed afterwards just as with ruby’s builtin File.open method.
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
# File 'lib/zip/file.rb', line 233 def get_output_stream(entry, = nil, comment = nil, extra = nil, compressed_size = nil, crc = nil, compression_method = nil, size = nil, time = nil, &aProc) newEntry = if entry.kind_of?(Entry) entry else Entry.new(@name, entry.to_s, comment, extra, compressed_size, crc, compression_method, size, time) end if newEntry.directory? raise ArgumentError, "cannot open stream to directory entry - '#{newEntry}'" end newEntry.unix_perms = zipStreamableEntry = StreamableStream.new(newEntry) @entry_set << zipStreamableEntry zipStreamableEntry.get_output_stream(&aProc) end |
#glob(*args, &block) ⇒ Object
Searches for entries given a glob
344 345 346 |
# File 'lib/zip/file.rb', line 344 def glob(*args, &block) @entry_set.glob(*args, &block) end |
#mkdir(entryName, permissionInt = 0755) ⇒ Object
Creates a directory
362 363 364 365 366 367 368 369 |
# File 'lib/zip/file.rb', line 362 def mkdir(entryName, = 0755) if find_entry(entryName) raise Errno::EEXIST, "File exists - #{entryName}" end entryName = entryName.dup.to_s entryName << '/' unless entryName.end_with?('/') @entry_set << ::Zip::StreamableDirectory.new(@name, entryName, nil, ) end |
#read(entry) ⇒ Object
Returns a string containing the contents of the specified entry
256 257 258 |
# File 'lib/zip/file.rb', line 256 def read(entry) get_input_stream(entry) { |is| is.read } end |
#remove(entry) ⇒ Object
Removes the specified entry.
270 271 272 |
# File 'lib/zip/file.rb', line 270 def remove(entry) @entry_set.delete(get_entry(entry)) end |
#rename(entry, new_name, &continue_on_exists_proc) ⇒ Object
Renames the specified entry.
275 276 277 278 279 280 281 |
# File 'lib/zip/file.rb', line 275 def rename(entry, new_name, &continue_on_exists_proc) foundEntry = get_entry(entry) check_entry_exists(new_name, continue_on_exists_proc, 'rename') @entry_set.delete(foundEntry) foundEntry.name = new_name @entry_set << foundEntry end |
#replace(entry, srcPath) ⇒ Object
Replaces the specified entry with the contents of srcPath (from the file system).
285 286 287 288 289 |
# File 'lib/zip/file.rb', line 285 def replace(entry, srcPath) check_file(srcPath) remove(entry) add(entry, srcPath) end |
#to_s ⇒ Object
Returns the name of the zip archive
251 252 253 |
# File 'lib/zip/file.rb', line 251 def to_s @name end |
#write_buffer ⇒ Object
Write buffer write changes to buffer and return
316 317 318 319 320 321 |
# File 'lib/zip/file.rb', line 316 def write_buffer OutputStream.write_buffer do |zos| @entry_set.each { |e| e.write_to_zip_output_stream(zos) } zos.comment = comment end end |