Class: Database::Tree

Inherits:
Object
  • Object
show all
Defined in:
lib/database/tree.rb

Constant Summary collapse

ENTRY_FORMAT =
"Z*H40"
TREE_MODE =
040000

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(entries = {}) ⇒ Tree

Returns a new instance of Tree.



36
37
38
# File 'lib/database/tree.rb', line 36

def initialize(entries = {})
  @entries = entries
end

Instance Attribute Details

#entriesObject (readonly)

Returns the value of attribute entries.



8
9
10
# File 'lib/database/tree.rb', line 8

def entries
  @entries
end

#oidObject

Returns the value of attribute oid.



7
8
9
# File 'lib/database/tree.rb', line 7

def oid
  @oid
end

Class Method Details

.build(entries) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/database/tree.rb', line 26

def self.build(entries)
  root = Tree.new

  entries.each do |entry|
    root.add_entry(entry.parent_directories, entry)
  end

  root
end

.parse(scanner) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/database/tree.rb', line 10

def self.parse(scanner)
  entries = {}

  until scanner.eos?
    mode = scanner.scan_until(/ /).strip.to_i(8)
    name = scanner.scan_until(/\0/)[0..-2]

    oid = scanner.peek(20).unpack("H40").first
    scanner.pos += 20

    entries[name] = Entry.new(oid, mode)
  end

  Tree.new(entries)
end

Instance Method Details

#add_entry(parents, entry) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/database/tree.rb', line 40

def add_entry(parents, entry)
  if parents.empty?
    @entries[entry.basename] = entry
  else
    tree = @entries[parents.first.basename] ||= Tree.new
    tree.add_entry(parents.drop(1), entry)
  end
end

#modeObject



56
57
58
# File 'lib/database/tree.rb', line 56

def mode
  TREE_MODE
end

#to_sObject



64
65
66
67
68
69
70
71
# File 'lib/database/tree.rb', line 64

def to_s
  entries = @entries.map do |name, entry|
    mode = entry.mode.to_s(8)
    ["#{ mode } #{ name }", entry.oid].pack(ENTRY_FORMAT)
  end

  entries.join("")
end

#traverse(&block) ⇒ Object



49
50
51
52
53
54
# File 'lib/database/tree.rb', line 49

def traverse(&block)
  @entries.each do |name, entry|
    entry.traverse(&block) if entry.is_a?(Tree)
  end
  block.call(self)
end

#typeObject



60
61
62
# File 'lib/database/tree.rb', line 60

def type
  "tree"
end