summaryrefslogtreecommitdiff
path: root/lib/oxidized/output/git.rb
blob: b4fa4a8f579265bde17a1b51ed6069c4f4755589 (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
64
65
66
67
module Oxidized
class Git < Output
  require 'grit'
  require 'oxidized/fix/grit' if RUBY_VERSION[0..1] == '2.'
  include Grit

  def initialize
    @cfg = CFG.output[:git]
  end

  def setup
    if not @cfg
      CFG.output[:git] = {
        :user  => 'Oxidized',
        :email => 'o@example.com',
        :repo  => File.join(Config::Root, 'oxidized.git')
      }
      CFG.save
    end
  end

  def store file, data, opt={}
    msg   = opt[:msg]
    user  = (opt[:user]  or @cfg[:user])
    email = (opt[:email] or @cfg[:email])
    repo  = @cfg[:repo]
    if opt[:group]
      repo = File.join File.dirname(repo), opt[:group] + '.git'
    end
    begin
      repo = Repo.new repo
      actor = Actor.new user, email
      update_repo repo, file, data, msg, actor
    rescue Grit::NoSuchPathError
      Repo.init_bare repo
      retry
    rescue Grit::Git::GitTimeout
      Log.error "git timeout for #{file}"
    end
  end

  def fetch node, group
    begin
      repo = Repo.new(@cfg[:repo])
      (repo.tree / node).data
    rescue
      'node not found'
    end
  end

  private

  def update_repo repo, file, data, msg, actor
    index  = repo.index
    index.read_tree 'master'
    old = index.write_tree index.tree, index.current_tree
    index.add file, data
    new = index.write_tree index.tree, index.current_tree
    if old != new
      parent = repo.commits(nil, 1).first
      parent = [parent] if parent
      Log.debug "GIT: comitting #{file}"
      index.commit msg, parent, actor
    end
  end
end
end