module CommitMsgUrlShortener class HookScript attr_reader :name def initialize git_path @name = 'commit-msg' @hook_path = File.expand_path File.join(git_path, ".git/hooks/#{@name}") end def append_code code remove_code open('a+b') {|file| file.puts "#{code}"} end def interpreter @interpreter ||= begin return unless exist? interpreter = nil open('rb') do |file| shebang_line = '' file.each_line{|line| shebang_line = line if line.index '#!'} INTERPRETERS.each{|name| interpreter = name if shebang_line.downcase.index name} end interpreter end end def remove_code new_lines = [] removed_lines = [] return removed_lines unless exist? open('rb') do |file| file.each_line do |line| unless line.downcase.index BIN_NAME.downcase new_lines << line else removed_lines << line end end end open('wb') do |file| new_lines.each{|line| file.puts line} end removed_lines end def get_used_service lines_call_the_gem = [] service = nil return service unless exist? open('rb') do |file| file.each_line {|line| lines_call_the_gem << line if line.downcase.index(BIN_NAME.downcase)} if lines_call_the_gem.size > 1 raise "It appears that there are multiple calls to #{BIN_NAME} in your #{name} hook." end unless lines_call_the_gem.empty? service = SERVICES.select{|s| lines_call_the_gem.first.include? s.name}.first raise "It appears that your are using an unknow service." unless service end end service end def exist? File.exist? @hook_path end def create open('wb') {|file| file.puts "#!/bin/sh"} @interpreter = 'sh' make_executable end private def make_executable command = 'chmod ug+x "'+@hook_path+'" >/dev/null 2>&1' system_result = system(command) rescue false raise "I was unable to make the file #{@hook_path} executable." unless system_result end def open mode, &block File.send :open, @hook_path, mode, &block end end end