Keep storages as instance variables
[git/ruby-binding.git] / git.rb
blob73aec9ab2253b86b48967a5252cf44047442763a
1 require 'git/internal/object'
2 require 'git/internal/pack'
3 require 'git/internal/loose'
4 require 'git/object'
6 module Git
7   class Repository
8     def initialize(git_dir)
9       @git_dir = git_dir
10       @loose = Internal::LooseStorage.new("#@git_dir/objects")
11       @packs = []
12       initpacks
13     end
15     def get_object_by_sha1(sha1)
16       r = get_raw_object_by_sha1(sha1)
17       return nil if !r
18       Object.from_raw(r, self)
19     end
21     def get_raw_object_by_sha1(sha1)
22       sha1 = [sha1].pack("H*")
24       # try packs
25       @packs.each do |pack|
26         o = pack[sha1]
27         return o if o
28       end
30       # try loose storage
31       o = @loose[sha1]
32       return o if o
34       # try packs again, maybe the object got packed in the meantime
35       initpacks
36       @packs.each do |pack|
37         o = pack[sha1]
38         return o if o
39       end
41       nil
42     end
44     def initpacks
45       @packs.each do |pack|
46         pack.close
47       end
48       @packs = []
49       Dir.glob("#@git_dir/objects/pack/pack-*.pack").each do |pack|
50         @packs << Git::Internal::PackStorage.new(pack)
51       end
52     end
53   end
54 end
56 if $0 == __FILE__ 
57   require 'git' 
58   r = Git::Repository.new(ARGV[0]) 
59   ARGV[1..-1].each do |sha1| 
60     o = r.get_object_by_sha1(sha1) 
61     if !o 
62       puts 'no such object' 
63       next 
64     end 
65     puts o.type 
66     case o.type 
67     when :blob 
68       puts o.content 
69     when :tree 
70       puts o.entry.collect { |e| "%s %s" % [e.sha1, e.name] }.join("\n") 
71     when :commit 
72       puts o.raw_content 
73     when :tag 
74       puts o.raw_content 
75     end 
76   end 
77 end