#!/usr/bin/env ruby require 'uri' require 'net/http' require 'open3' require 'yaml' class Options def initialize(args) @args = args end def verb @args[0] end def hipchat_token ci_config["hipchat_token"] end def hipchat_room ci_config["hipchat_room"] end def matchers ci_config["matchers"] end def url_prefix ci_config["url_prefix"] end def valid? [ "fail", "success" ].include?(verb) && !ci_config.nil? && hipchat_token && hipchat_room && matchers end private def ci_config config_file_name = "./ci/config.yml" if File.exists?(config_file_name) @ci_config ||= YAML.load_file("./ci/config.yml") else nil end end end class Git def initialize(matchers) @matchers = matchers end def last_comitter_name map_comitter_name `git log -1 "--pretty=format:%an"` end def last_commit_sha `git log -1 "--pretty=format:%h"` end def last_commit_time `git log -1 "--pretty=format:%ai"` end private def map_comitter_name(name) @matchers.each { |regex, value| return value if regex.match(name) } return "Юзернейм" end end class TalkingRamil class << self def announce(what, hero, url_prefix=nil) puts "Announcing #{what} for #{hero}" send_ramil_request(url_prefix || "http://192.168.10.32:8082/build", what, hero: hero) end private def send_ramil_request(url_prefix, verb, params={}) Net::HTTP.post_form(URI.parse("#{url_prefix}/#{verb}"), params) end end end class Hipchat class << self def announce(token, room, what, moment, hash, hero) send("announce_#{what}", token, room, moment, hash, hero) end private def announce_success(token, room, moment, hash, hero) message = %Q|#{hash} #{hero} @ #{moment}
Зелёный билд, дамы и господа!| send_hipchat(token, room, "green", message) end def announce_fail(token, room, moment, hash, hero) message = %Q|#{hash} #{hero} @ #{moment}
Билд безнадёжно сломан!| send_hipchat(token, room, "red", message) end def send_hipchat(token, room, color, text) stdin, stdout_and_stderr, wait_thr = Open3.popen2e(File.expand_path("../hipchat_room_message", __FILE__), "-t", token, "-f", "CI", "-c", color, "-r", room, "-n") stdin.write(text) stdin.close stdout_and_stderr.close end end end opts = Options.new(ARGV) unless opts.valid? puts "usage: uniq-ci-report success|fail" puts "\nci/config.yml must contain: 'hipchat_token', 'hipchat_room' and 'matchers' keys" exit(-1) end git = Git.new(opts.matchers) Hipchat.announce(opts.hipchat_token, opts.hipchat_room, opts.verb, git.last_commit_time, git.last_commit_sha, git.last_comitter_name) TalkingRamil.announce(opts.verb, git.last_comitter_name, opts.url_prefix) case opts.verb when "success" exit(0) when "fail" exit(1) else raise "Unknown verb: #{opts.verb}" end