#!/usr/bin/env ruby
incpath = File.dirname(__FILE__)
$: << incpath
require 'rails_env'
require 'date'
gitdir = File.expand_path(File.join(incpath, ".."))
repository_name = File.basename(gitdir)
slug = ""
if repository_name =~ /\.git$/
repository_name.sub!(/\.git$/, "")
slug = File.basename(File.expand_path(File.join(gitdir, "..")))
end
git = Grit::Git.new(gitdir)
while line = gets
#puts "@@> #{line.inspect}"
# 3b480c5c30962c9f5b82a9c61a75992dc605de21 ee27ee3a022802c0569f9cdef6e9ad29aea096a8 refs/heads/master\n
oldrev, newrev, revname = line.split(" ")
current_rev = newrev
newtype = oldtype = current_rev_type = "commit"
action = :create
if oldrev =~ /^0+$/
action = :create
else
if newrev =~ /^0+$/
action = :delete
else
action = :update
end
end
if action != :delete
newtype = git.cat_file({:t => true}, newrev)
end
if action == :update
oldtype = git.cat_file({:t => true}, oldrev)
end
if action == :delete
current_rev = oldrev
current_rev_type = oldtype
end
# type => heads, tags, remotes
# name => branch name
path, type, name = revname.split("/")
info = git.show({ :pretty => "format:author: %cn%nemail: %ce%ndate: %cd%nmessage: %s", :s => true}, current_rev )
hash = {}
info.each { |line|
if line =~ /(\w+):\s(.*)$/
key = $1.to_sym
value = $2
value = Date.parse(value) if key == :date
hash[key] = value
end
}
# action => create, delete, update
# rev_type => commit, tag
user = User.find_by_email(hash[:email])
if user.nil?
# TODO: no user should be ok, no need to skip
$stdout.puts "** The email '#{hash[:email]}' is not registered."
next
end
project = Project.find_by_slug(slug)
repository = nil
project.repositories.each { |repo|
if repo.name == repository_name
repository = repo
break
end
}
action_id = nil
ref = nil
if current_rev_type == "commit"
if type == "heads"
case action
when :create
action_id = Action::CREATE_BRANCH
ref = name
when :update
action_id = Action::COMMIT
ref = current_rev
when :delete
action_id = Action::DELETE_BRANCH
ref = name
end
elsif type == "tags"
if action == :create
action_id = Action::CREATE_TAG
ref = name
elsif action == :delete
action_id = Action::DELETE_TAG
ref = name
end
end
elsif current_rev_type == "tag"
if type == "tags"
if action == :create
action_id = Action::CREATE_TAG
ref = name
elsif action == :delete
action_id = Action::DELETE_TAG
ref = name
end
end
end
next unless action_id
# puts "#{hash[:author]}: #{Action.name(action_id)} #{ref} on #{slug} [#{hash[:date]}]"
# puts " #{hash[:message]}"
project.create_event(action_id, repository, user, ref, hash[:message])
end
puts "[OK]"