Class: Zip::File

Inherits:
Object
  • Object
show all
Extended by:
Forwardable, FileSplit
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", create: true) {
 |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", create: true) {
  |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

IO_METHODS =
[:tell, :seek, :read, :eof, :close].freeze

Constants included from FileSplit

Zip::FileSplit::DATA_BUFFER_SIZE, Zip::FileSplit::MAX_SEGMENT_SIZE, Zip::FileSplit::MIN_SEGMENT_SIZE

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from FileSplit

get_partial_zip_file_name, get_segment_count_for_split, get_segment_size_for_split, put_split_signature, save_splited_part, split

Methods included from FileSystem

#dir, #file

Constructor Details

#initialize(path_or_io, create: false, buffer: false, **options) ⇒ File

Opens a zip archive. Pass create: true to create a new archive if it doesn't exist already.


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/zip/file.rb', line 71

def initialize(path_or_io, create: false, buffer: false, **options)
  super()
  options  = DEFAULT_RESTORE_OPTIONS
             .merge(compression_level: ::Zip.default_compression)
             .merge(options)
  @name    = path_or_io.respond_to?(:path) ? path_or_io.path : path_or_io
  @create  = create ? true : false # allow any truthy value to mean true

  initialize_cdir(path_or_io, buffer: buffer)

  @restore_ownership   = options[:restore_ownership]
  @restore_permissions = options[:restore_permissions]
  @restore_times       = options[:restore_times]
  @compression_level   = options[:compression_level]
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.


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

def name
  @name
end

#restore_ownershipObject

default -> false.


59
60
61
# File 'lib/zip/file.rb', line 59

def restore_ownership
  @restore_ownership
end

#restore_permissionsObject

default -> true.


62
63
64
# File 'lib/zip/file.rb', line 62

def restore_permissions
  @restore_permissions
end

#restore_timesObject

default -> true.


65
66
67
# File 'lib/zip/file.rb', line 65

def restore_times
  @restore_times
end

Class Method Details

.count_entries(path_or_io) ⇒ Object

Count the entries in a zip archive without reading the whole set of entry data into memory.


140
141
142
143
144
145
146
147
148
149
150
# File 'lib/zip/file.rb', line 140

def count_entries(path_or_io)
  cdir = ::Zip::CentralDirectory.new

  if path_or_io.kind_of?(String)
    ::File.open(path_or_io, 'rb') do |f|
      cdir.count_entries(f)
    end
  else
    cdir.count_entries(path_or_io)
  end
end

.foreach(zip_file_name, &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).


132
133
134
135
136
# File 'lib/zip/file.rb', line 132

def foreach(zip_file_name, &block)
  ::Zip::File.open(zip_file_name) do |zip_file|
    zip_file.each(&block)
  end
end

.open(file_name, create: false, **options) ⇒ Object

Similar to ::new. If a block is passed the Zip::File object is passed to the block and is automatically closed afterwards, just as with ruby's builtin File::open method.


91
92
93
94
95
96
97
98
99
100
# File 'lib/zip/file.rb', line 91

def open(file_name, create: false, **options)
  zf = ::Zip::File.new(file_name, create: create, **options)
  return zf unless block_given?

  begin
    yield zf
  ensure
    zf.close
  end
end

.open_buffer(io = ::StringIO.new, create: false, **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.)

Yields:

  • (zf)

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/zip/file.rb', line 106

def open_buffer(io = ::StringIO.new, create: false, **options)
  unless IO_METHODS.map { |method| io.respond_to?(method) }.all? || io.kind_of?(String)
    raise 'Zip::File.open_buffer expects a String or IO-like argument' \
          "(responds to #{IO_METHODS.join(', ')}). Found: #{io.class}"
  end

  io = ::StringIO.new(io) if io.kind_of?(::String)

  zf = ::Zip::File.new(io, create: create, buffer: true, **options)
  return zf unless block_given?

  yield zf

  begin
    zf.write_buffer(io)
  rescue IOError => e
    raise unless e.message == 'not opened for writing'
  end
end

Instance Method Details

#add(entry, src_path, &continue_on_exists_proc) ⇒ Object

Convenience method for adding the contents of a file to the archive


202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/zip/file.rb', line 202

def add(entry, src_path, &continue_on_exists_proc)
  continue_on_exists_proc ||= proc { ::Zip.continue_on_exists_proc }
  check_entry_exists(entry, continue_on_exists_proc, 'add')
  new_entry = if entry.kind_of?(::Zip::Entry)
                entry
              else
                ::Zip::Entry.new(
                  @name, entry.to_s,
                  compression_level: @compression_level
                )
              end
  new_entry.gather_fileinfo_from_srcpath(src_path)
  @cdir << new_entry
end

#add_stored(entry, src_path, &continue_on_exists_proc) ⇒ Object

Convenience method for adding the contents of a file to the archive in Stored format (uncompressed)


219
220
221
222
223
224
# File 'lib/zip/file.rb', line 219

def add_stored(entry, src_path, &continue_on_exists_proc)
  entry = ::Zip::Entry.new(
    @name, entry.to_s, compression_method: ::Zip::Entry::STORED
  )
  add(entry, src_path, &continue_on_exists_proc)
end

#closeObject

Closes the zip file committing any changes that has been made.


284
285
286
# File 'lib/zip/file.rb', line 284

def close
  commit
end

#commitObject

Commits changes that has been made since the previous commit to the zip archive.


257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/zip/file.rb', line 257

def commit
  return if name.kind_of?(StringIO) || !commit_required?

  on_success_replace do |tmp_file|
    ::Zip::OutputStream.open(tmp_file) do |zos|
      @cdir.each do |e|
        e.write_to_zip_output_stream(zos)
        e.clean_up
      end
      zos.comment = comment
    end
    true
  end
  initialize_cdir(@name)
end

#commit_required?Boolean

Returns true if any changes has been made to this archive since the previous commit

Returns:

  • (Boolean)

290
291
292
293
294
295
296
297
298
# File 'lib/zip/file.rb', line 290

def commit_required?
  return true if @create || @cdir.dirty?

  @cdir.each do |e|
    return true if e.dirty?
  end

  false
end

#extract(entry, dest_path, &block) ⇒ Object

Extracts entry to file dest_path.


249
250
251
252
253
# File 'lib/zip/file.rb', line 249

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


302
303
304
305
306
307
308
309
310
# File 'lib/zip/file.rb', line 302

def find_entry(entry_name)
  selected_entry = @cdir.find_entry(entry_name)
  return if selected_entry.nil?

  selected_entry.restore_ownership   = @restore_ownership
  selected_entry.restore_permissions = @restore_permissions
  selected_entry.restore_times       = @restore_times
  selected_entry
end

#get_entry(entry) ⇒ Object

Searches for an entry just as find_entry, but throws Errno::ENOENT if no entry is found.

Raises:

  • (Errno::ENOENT)

314
315
316
317
318
319
# File 'lib/zip/file.rb', line 314

def get_entry(entry)
  selected_entry = find_entry(entry)
  raise Errno::ENOENT, entry if selected_entry.nil?

  selected_entry
end

#get_input_stream(entry, &a_proc) ⇒ 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.


156
157
158
# File 'lib/zip/file.rb', line 156

def get_input_stream(entry, &a_proc)
  get_entry(entry).get_input_stream(&a_proc)
end

#get_output_stream(entry, permissions: nil, comment: nil, extra: nil, compressed_size: nil, crc: nil, compression_method: nil, compression_level: nil, size: nil, time: nil, &a_proc) ⇒ 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.


165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/zip/file.rb', line 165

def get_output_stream(entry, permissions: nil, comment: nil,
                      extra: nil, compressed_size: nil, crc: nil,
                      compression_method: nil, compression_level: nil,
                      size: nil, time: nil, &a_proc)

  new_entry =
    if entry.kind_of?(Entry)
      entry
    else
      Entry.new(
        @name, entry.to_s, comment: comment, extra: extra,
        compressed_size: compressed_size, crc: crc, size: size,
        compression_method: compression_method,
        compression_level: compression_level, time: time
      )
    end
  if new_entry.directory?
    raise ArgumentError,
          "cannot open stream to directory entry - '#{new_entry}'"
  end
  new_entry.unix_perms = permissions
  zip_streamable_entry = StreamableStream.new(new_entry)
  @cdir << zip_streamable_entry
  zip_streamable_entry.get_output_stream(&a_proc)
end

#mkdir(entry_name, permission = 0o755) ⇒ Object

Creates a directory

Raises:

  • (Errno::EEXIST)

322
323
324
325
326
327
328
# File 'lib/zip/file.rb', line 322

def mkdir(entry_name, permission = 0o755)
  raise Errno::EEXIST, "File exists - #{entry_name}" if find_entry(entry_name)

  entry_name = entry_name.dup.to_s
  entry_name << '/' unless entry_name.end_with?('/')
  @cdir << ::Zip::StreamableDirectory.new(@name, entry_name, nil, permission)
end

#read(entry) ⇒ Object

Returns a string containing the contents of the specified entry


197
198
199
# File 'lib/zip/file.rb', line 197

def read(entry)
  get_input_stream(entry, &:read)
end

#remove(entry) ⇒ Object

Removes the specified entry.


227
228
229
# File 'lib/zip/file.rb', line 227

def remove(entry)
  @cdir.delete(get_entry(entry))
end

#rename(entry, new_name, &continue_on_exists_proc) ⇒ Object

Renames the specified entry.


232
233
234
235
236
237
238
# File 'lib/zip/file.rb', line 232

def rename(entry, new_name, &continue_on_exists_proc)
  found_entry = get_entry(entry)
  check_entry_exists(new_name, continue_on_exists_proc, 'rename')
  @cdir.delete(found_entry)
  found_entry.name = new_name
  @cdir << found_entry
end

#replace(entry, src_path) ⇒ Object

Replaces the specified entry with the contents of src_path (from the file system).


242
243
244
245
246
# File 'lib/zip/file.rb', line 242

def replace(entry, src_path)
  check_file(src_path)
  remove(entry)
  add(entry, src_path)
end

#to_sObject

Returns the name of the zip archive


192
193
194
# File 'lib/zip/file.rb', line 192

def to_s
  @name
end

#write_buffer(io = ::StringIO.new) ⇒ Object

Write buffer write changes to buffer and return


274
275
276
277
278
279
280
281
# File 'lib/zip/file.rb', line 274

def write_buffer(io = ::StringIO.new)
  return unless commit_required?

  ::Zip::OutputStream.write_buffer(io) do |zos|
    @cdir.each { |e| e.write_to_zip_output_stream(zos) }
    zos.comment = comment
  end
end