Blob of vendor/grit/lib/grit/tree.rb (raw blob data)

1 module Grit
2
3 class Tree
4 lazy_reader :contents
5 attr_reader :id
6 attr_reader :mode
7 attr_reader :name
8
9 # Construct the contents of the tree
10 # +repo+ is the Repo
11 # +treeish+ is the reference
12 # +paths+ is an optional Array of directory paths to restrict the tree
13 #
14 # Returns Grit::Tree (baked)
15 def self.construct(repo, treeish, paths = [])
16 output = repo.git.ls_tree({}, treeish, *paths)
17
18 self.allocate.construct_initialize(repo, treeish, output)
19 end
20
21 def construct_initialize(repo, id, text)
22 @repo = repo
23 @id = id
24 @contents = []
25
26 text.split("\n").each do |line|
27 @contents << content_from_string(repo, line)
28 end
29 @contents.compact!
30
31 self
32 end
33
34 def lazy_source
35 Tree.construct(@repo, @id, [])
36 end
37
38 # Create an unbaked Tree containing just the specified attributes
39 # +repo+ is the Repo
40 # +atts+ is a Hash of instance variable data
41 #
42 # Returns Grit::Tree (unbaked)
43 def self.create(repo, atts)
44 self.allocate.create_initialize(repo, atts)
45 end
46
47 # Initializer for Tree.create
48 # +repo+ is the Repo
49 # +atts+ is a Hash of instance variable data
50 #
51 # Returns Grit::Tree (unbaked)
52 def create_initialize(repo, atts)
53 @repo = repo
54
55 atts.each do |k, v|
56 instance_variable_set("@#{k}", v)
57 end
58 self
59 end
60
61 # Parse a content item and create the appropriate object
62 # +repo+ is the Repo
63 # +text+ is the single line containing the items data in `git ls-tree` format
64 #
65 # Returns Grit::Blob or Grit::Tree
66 def content_from_string(repo, text)
67 mode, type, id, name = text.split(" ", 4)
68 case type
69 when "tree"
70 Tree.create(repo, :id => id, :mode => mode, :name => name)
71 when "blob"
72 Blob.create(repo, :id => id, :mode => mode, :name => name)
73 when "commit"
74 nil
75 else
76 raise "Invalid type: #{type}"
77 end
78 end
79
80 # Find the named object in this tree's contents
81 #
82 # Examples
83 # Repo.new('/path/to/grit').tree/'lib'
84 # # => #<Grit::Tree "6cc23ee138be09ff8c28b07162720018b244e95e">
85 # Repo.new('/path/to/grit').tree/'README.txt'
86 # # => #<Grit::Blob "8b1e02c0fb554eed2ce2ef737a68bb369d7527df">
87 #
88 # Returns Grit::Blob or Grit::Tree or nil if not found
89 def /(file)
90 self.contents.select { |c| c.name == file }.first
91 end
92
93 def basename
94 File.basename(@name)
95 end
96
97 # Pretty object inspection
98 def inspect
99 %Q{#<Grit::Tree "#{@id}">}
100 end
101 end # Tree
102
103 end # Grit