Class: Zip::File

Inherits:
Object
  • Object
show all
Extended by:
Forwardable, FileSplit
Includes:
Enumerable, FileSystem
Defined in:
lib/zip/file.rb,
lib/zip/filesystem.rb

Overview

:nodoc:

Constant Summary collapse

IO_METHODS =

:nodoc:

[: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, restore_ownership: , restore_permissions: , restore_times: , compression_level: ::Zip.default_compression, suppress_extra_fields: false) ⇒ File

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



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/zip/file.rb', line 76

def initialize(path_or_io, create: false, buffer: false,
               restore_ownership: DEFAULT_RESTORE_OPTIONS[:restore_ownership],
               restore_permissions: DEFAULT_RESTORE_OPTIONS[:restore_permissions],
               restore_times: DEFAULT_RESTORE_OPTIONS[:restore_times],
               compression_level: ::Zip.default_compression,
               suppress_extra_fields: false)
  super()

  @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     = restore_ownership
  @restore_permissions   = restore_permissions
  @restore_times         = restore_times
  @compression_level     = compression_level
  @suppress_extra_fields = suppress_extra_fields
end

Instance Attribute Details

#nameObject (readonly)

The name of this zip archive.



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

def name
  @name
end

#restore_ownershipObject

default -> false.



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

def restore_ownership
  @restore_ownership
end

#restore_permissionsObject

default -> true.



67
68
69
# File 'lib/zip/file.rb', line 67

def restore_permissions
  @restore_permissions
end

#restore_timesObject

default -> true.



70
71
72
# File 'lib/zip/file.rb', line 70

def restore_times
  @restore_times
end

Class Method Details

.add_recursive(zip_file_name, src_dir, prefix: '', max_depth: 16, &continue_on_exists_proc) ⇒ Object

Recursively adds the contents of src_dir to the new archive zip_file_name, nested under prefix if given (the archive root otherwise). src_dir itself is not added, only its contents.

Symlinks are ignored (skipped, with a warning) rather than followed or added, to avoid the security issues they can pose. max_depth limits how many directory levels below src_dir are walked; anything deeper is skipped, also with a warning (default: 16).



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

def add_recursive(zip_file_name, src_dir, prefix: '', max_depth: 16, &continue_on_exists_proc)
  Zip::File.open(zip_file_name, create: true) do |zf|
    zf.add_recursive(src_dir, prefix: prefix, max_depth: max_depth, &continue_on_exists_proc)
  end
end

.count_entries(path_or_io) ⇒ Object

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



171
172
173
174
175
176
177
178
179
180
181
# File 'lib/zip/file.rb', line 171

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

.extract_all(zip_file_name, destination_directory = '.', &block) ⇒ Object

Extracts every entry in the zip archive zip_file_name into destination_directory, preserving the archive's directory structure.



199
200
201
202
203
# File 'lib/zip/file.rb', line 199

def extract_all(zip_file_name, destination_directory = '.', &block)
  Zip::File.open(zip_file_name) do |zf|
    zf.extract_all(destination_directory, &block)
  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).



163
164
165
166
167
# File 'lib/zip/file.rb', line 163

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, restore_ownership: , restore_permissions: , restore_times: , compression_level: ::Zip.default_compression, suppress_extra_fields: false) ⇒ 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.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/zip/file.rb', line 100

def open(file_name, create: false,
         restore_ownership: DEFAULT_RESTORE_OPTIONS[:restore_ownership],
         restore_permissions: DEFAULT_RESTORE_OPTIONS[:restore_permissions],
         restore_times: DEFAULT_RESTORE_OPTIONS[:restore_times],
         compression_level: ::Zip.default_compression,
         suppress_extra_fields: false)
  zf = ::Zip::File.new(file_name, create:                create,
                                  restore_ownership:     restore_ownership,
                                  restore_permissions:   restore_permissions,
                                  restore_times:         restore_times,
                                  compression_level:     compression_level,
                                  suppress_extra_fields: suppress_extra_fields)

  return zf unless block_given?

  begin
    yield zf
  ensure
    zf.close
  end
end

.open_buffer(io = ::StringIO.new, create: false, restore_ownership: , restore_permissions: , restore_times: , compression_level: ::Zip.default_compression, suppress_extra_fields: false) {|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)


126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/zip/file.rb', line 126

def open_buffer(io = ::StringIO.new, create: false,
                restore_ownership: DEFAULT_RESTORE_OPTIONS[:restore_ownership],
                restore_permissions: DEFAULT_RESTORE_OPTIONS[:restore_permissions],
                restore_times: DEFAULT_RESTORE_OPTIONS[:restore_times],
                compression_level: ::Zip.default_compression,
                suppress_extra_fields: false)
  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,
                           restore_ownership:     restore_ownership,
                           restore_permissions:   restore_permissions,
                           restore_times:         restore_times,
                           compression_level:     compression_level,
                           suppress_extra_fields: suppress_extra_fields)

  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



254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/zip/file.rb', line 254

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_recursive(src_dir, prefix: '', max_depth: 16, &continue_on_exists_proc) ⇒ Object

Recursively adds the contents of src_dir to the archive, nested under prefix if given (the archive root otherwise). src_dir itself is not added, only its contents.

Symlinks are ignored (skipped, with a warning) rather than followed or added, to avoid the security issues they can pose. max_depth limits how many directory levels below src_dir are walked; anything deeper is skipped, also with a warning (default: 16).

Raises:

  • (Errno::ENOENT)


286
287
288
289
290
291
292
293
294
295
# File 'lib/zip/file.rb', line 286

def add_recursive(src_dir, prefix: '', max_depth: 16, &continue_on_exists_proc)
  raise Errno::ENOENT, src_dir unless ::File.directory?(src_dir)
  raise ArgumentError, 'max_depth must be at least 1' if max_depth < 1

  prefix = prefix.to_s
  prefix += '/' unless prefix.empty? || prefix.end_with?('/')

  add_recursive_dir(prefix, src_dir, 1, max_depth, continue_on_exists_proc)
  self
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)



271
272
273
274
275
276
# File 'lib/zip/file.rb', line 271

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.



387
388
389
# File 'lib/zip/file.rb', line 387

def close
  commit
end

#commitObject

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



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/zip/file.rb', line 360

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

  on_success_replace do |tmp_file|
    ::Zip::OutputStream.open(tmp_file, suppress_extra_fields: @suppress_extra_fields) 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)


393
394
395
396
397
398
399
400
401
# File 'lib/zip/file.rb', line 393

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

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

  false
end

#extract(entry, entry_path = nil, destination_directory: '.', &block) ⇒ Object

Extracts entry to a file at entry_path, with destination_directory as the base location in the filesystem.

NB: The caller is responsible for making sure destination_directory is safe, if it is passed.



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

def extract(entry, entry_path = nil, destination_directory: '.', &block)
  block ||= proc { ::Zip.on_exists_proc }
  found_entry = get_entry(entry)
  entry_path ||= found_entry.name
  found_entry.extract(entry_path, destination_directory: destination_directory, &block)
end

#extract_all(destination_directory = '.', &block) ⇒ Object

Extracts every entry in the archive into destination_directory, preserving the archive's directory structure.

Symlink entries are ignored (skipped, with a warning) rather than extracted. See Entry#extract for the path-safety checks applied to every other entry.

NB: The caller is responsible for making sure destination_directory is safe, if it is passed.



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/zip/file.rb', line 340

def extract_all(destination_directory = '.', &block)
  # Partition the entries into directories and non-directories, so that
  # directories are created first.
  dirs, others = entries.partition(&:directory?)

  (dirs + others).each do |entry|
    if entry.symlink?
      warn "WARNING: skipped symlink '#{entry.name}' during extract_all."
      next
    end

    entry.extract(entry.name, destination_directory:     destination_directory,
                              create_parent_directories: true, &block)
  end

  self
end

#find_entry(entry_name) ⇒ Object

Searches for entry with the specified name. Returns nil if no entry is found. See also get_entry



405
406
407
408
409
410
411
412
413
# File 'lib/zip/file.rb', line 405

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)


417
418
419
420
421
422
# File 'lib/zip/file.rb', line 417

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.



209
210
211
# File 'lib/zip/file.rb', line 209

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.



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/zip/file.rb', line 218

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)


425
426
427
428
429
430
431
# File 'lib/zip/file.rb', line 425

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



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

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

#remove(entry) ⇒ Object

Removes the specified entry.



298
299
300
# File 'lib/zip/file.rb', line 298

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

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

Renames the specified entry.



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

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).



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

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



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

def to_s
  @name
end

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

Write buffer write changes to buffer and return



377
378
379
380
381
382
383
384
# File 'lib/zip/file.rb', line 377

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

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