Class: Philiprehberger::Tar::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/tar/reader.rb

Overview

Reads and extracts tar archives.

Constant Summary collapse

BLOCK_SIZE =
512

Instance Method Summary collapse

Constructor Details

#initialize(io) ⇒ Reader

Returns a new instance of Reader.

Parameters:

  • io (IO)

    the input stream



10
11
12
# File 'lib/philiprehberger/tar/reader.rb', line 10

def initialize(io)
  @io = io
end

Instance Method Details

#each_entry {|Hash| ... } ⇒ Array<Hash>

Iterate over each entry in the archive.

Yields:

  • (Hash)

    entry info with :name, :size, :mode, :typeflag, :linkname, :content keys

Returns:

  • (Array<Hash>)

    entries if no block given



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/philiprehberger/tar/reader.rb', line 18

def each_entry(&block)
  entries = []

  loop do
    header = @io.read(BLOCK_SIZE)
    break if header.nil? || header.bytesize < BLOCK_SIZE
    break if header == "\0" * BLOCK_SIZE

    entry = parse_header(header)
    break if entry[:name].empty?

    if entry[:typeflag] == '2'
      # Symlink entry has no content
      entry[:content] = ''
    else
      content = read_content(entry[:size])
      entry[:content] = content
    end

    if block
      block.call(entry)
    else
      entries << entry
    end
  end

  entries unless block
end

#listArray<Hash>

List all entries without reading content.

Returns:

  • (Array<Hash>)

    entry info hashes with :name, :size, :mode, :typeflag, :linkname keys



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/philiprehberger/tar/reader.rb', line 50

def list
  result = []

  loop do
    header = @io.read(BLOCK_SIZE)
    break if header.nil? || header.bytesize < BLOCK_SIZE
    break if header == "\0" * BLOCK_SIZE

    entry = parse_header(header)
    break if entry[:name].empty?

    result << { name: entry[:name], size: entry[:size], mode: entry[:mode],
                typeflag: entry[:typeflag], linkname: entry[:linkname] }
    skip_content(entry[:size]) unless entry[:typeflag] == '2'
  end

  result
end