summaryrefslogtreecommitdiffstats
path: root/lib/git/raw/git.rb
blob: 004e795ce0535ed836532b181b532db192a28825 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
require 'git/internal/object'
require 'git/internal/pack'
require 'git/internal/loose'
require 'git/object'

module Git
  class Repository
    def initialize(git_dir)
      @git_dir = git_dir
      @loose = Internal::LooseStorage.new(git_path("objects"))
      @packs = []
      initpacks
    end

    def git_path(path)
      return "#@git_dir/#{path}"
    end

    def get_object_by_sha1(sha1)
      r = get_raw_object_by_sha1(sha1)
      return nil if !r
      Object.from_raw(r, self)
    end

    def get_raw_object_by_sha1(sha1)
      sha1 = [sha1].pack("H*")

      # try packs
      @packs.each do |pack|
        o = pack[sha1]
        return o if o
      end

      # try loose storage
      o = @loose[sha1]
      return o if o

      # try packs again, maybe the object got packed in the meantime
      initpacks
      @packs.each do |pack|
        o = pack[sha1]
        return o if o
      end

      nil
    end

    def initpacks
      @packs.each do |pack|
        pack.close
      end
      @packs = []
      Dir.open(git_path("objects/pack/")) do |dir|
        dir.each do |entry|
          if entry =~ /\.pack$/i
            @packs << Git::Internal::PackStorage.new(git_path("objects/pack/" \
                                                              + entry))
          end
        end
      end
    end
  end
end