5 class GitExecuteError < StandardError
18 def initialize(base = nil, logger = nil)
19 if base.is_a?(Git::Base)
20 @git_dir = base.repo.path
21 @git_index_file = base.index.path if base.index
22 @git_work_dir = base.dir.path if base.dir
23 elsif base.is_a?(Hash)
24 @git_dir = base[:repository]
25 @git_index_file = base[:index]
26 @git_work_dir = base[:working_directory]
37 # tries to clone the given repo
39 # returns {:repository} (if bare)
40 # {:working_directory} otherwise
43 # :remote - name of remote (rather than 'origin')
44 # :bare - no working directory
46 # TODO - make this work with SSH password or auth_key
48 def clone(repository, name, opts = {})
49 @path = opts[:path] || '.'
50 opts[:path] ? clone_dir = File.join(@path, name) : clone_dir = name
53 arr_opts << "--bare" if opts[:bare]
54 arr_opts << "-o #{opts[:remote]}" if opts[:remote]
55 arr_opts << repository
58 command('clone', arr_opts)
60 opts[:bare] ? {:repository => clone_dir} : {:working_directory => clone_dir}
67 def log_commits(opts = {})
68 arr_opts = ['--pretty=oneline']
69 arr_opts << "-#{opts[:count]}" if opts[:count]
70 arr_opts << "--since=\"#{opts[:since]}\"" if opts[:since].is_a? String
71 arr_opts << "#{opts[:between][0].to_s}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2)
72 arr_opts << opts[:object] if opts[:object].is_a? String
73 arr_opts << '-- ' + opts[:path_limiter] if opts[:path_limiter].is_a? String
75 command_lines('log', arr_opts, true).map { |l| l.split.first }
78 def full_log_commits(opts = {})
79 if !(opts[:since] || opts[:between] || opts[:path_limiter])
80 # can do this in pure ruby
81 sha = revparse(opts[:object] || branch_current || 'master')
82 count = opts[:count] || 30
84 if /\w{40}/.match(sha) # valid sha
86 return process_commit_data(repo.log(sha, count))
90 arr_opts = ['--pretty=raw']
91 arr_opts << "-#{opts[:count]}" if opts[:count]
92 arr_opts << "--since=\"#{opts[:since]}\"" if opts[:since].is_a? String
93 arr_opts << "#{opts[:between][0].to_s}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2)
94 arr_opts << opts[:object] if opts[:object].is_a? String
95 arr_opts << '-- ' + opts[:path_limiter] if opts[:path_limiter].is_a? String
97 full_log = command_lines('log', arr_opts, true)
98 process_commit_data(full_log)
102 if /\w{40}/.match(string) # passing in a sha - just no-op it
106 head = File.join(@git_dir, 'refs', 'heads', string)
107 return File.read(head).chomp if File.file?(head)
109 head = File.join(@git_dir, 'refs', 'remotes', string)
110 return File.read(head).chomp if File.file?(head)
112 head = File.join(@git_dir, 'refs', 'tags', string)
113 return File.read(head).chomp if File.file?(head)
115 command('rev-parse', string)
119 command('name-rev', string).split[1]
123 command('cat-file', ['-t', sha])
127 command('cat-file', ['-s', sha]).to_i
131 @raw_repo ||= Git::Raw::Repository.new(@git_dir)
134 # returns useful array of raw commit object data
137 cdata = get_raw_repo.cat_file(revparse(sha))
138 #cdata = command_lines('cat-file', ['commit', sha])
139 process_commit_data(cdata, sha)
142 def process_commit_data(data, sha = nil)
146 hsh = {'sha' => sha, 'message' => '', 'parent' => []}
153 if in_message && line != ''
154 hsh['message'] += line + "\n"
157 if (line != '') && !in_message
160 value = data.join(' ')
163 hsh_array << hsh if hsh
164 hsh = {'sha' => sha, 'message' => '', 'parent' => []}
171 elsif in_message && line == ''
179 hsh_array << hsh if hsh
186 def object_contents(sha)
187 #command('cat-file', ['-p', sha])
188 get_raw_repo.cat_file(revparse(sha)).chomp
192 data = {'blob' => {}, 'tree' => {}}
194 get_raw_repo.object(revparse(sha)).entry.each do |e|
195 data[e.format_type][e.name] = {:mode => e.format_mode, :sha => e.sha1}
198 #command_lines('ls-tree', sha.to_s).each do |line|
199 # (info, filenm) = line.split("\t")
200 # (mode, type, sha) = info.split
201 # data[type][filenm] = {:mode => mode, :sha => sha}
208 head = File.read(File.join(@git_dir, 'HEAD'))
211 if m = /ref: refs\/heads\/(.*)/.match(head)
214 arr += list_files('heads').map { |f| [f, f == current] }
215 arr += list_files('remotes').map { |f| [f, false] }
217 #command_lines('branch', '-a').each do |b|
219 # current = true if b[0, 2] == '* '
220 # arr << [b.gsub('* ', '').strip, current]
226 def list_files(ref_dir)
227 dir = File.join(@git_dir, 'refs', ref_dir)
229 Dir.chdir(dir) { files = Dir.glob('**/*').select { |f| File.file?(f) } }
234 branches_all.select { |b| b[1] }.first[0] rescue nil
239 # [tree-ish] = [[line_no, match], [line_no, match2]]
240 # [tree-ish] = [[line_no, match], [line_no, match2]]
241 def grep(string, opts = {})
242 opts[:object] = 'HEAD' if !opts[:object]
245 grep_opts << '-i' if opts[:ignore_case]
246 grep_opts << '-v' if opts[:invert_match]
247 grep_opts << "-e '#{string}'"
248 grep_opts << opts[:object] if opts[:object].is_a?(String)
249 grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
251 command_lines('grep', grep_opts).each do |line|
252 if m = /(.*)\:(\d+)\:(.*)/.match(line)
254 hsh[m[1]] << [m[2].to_i, m[3]]
260 def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
263 diff_opts << obj2 if obj2.is_a?(String)
264 diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
266 command('diff', diff_opts)
269 def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
270 diff_opts = ['--numstat']
272 diff_opts << obj2 if obj2.is_a?(String)
273 diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
275 hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
277 command_lines('diff', diff_opts).each do |file|
278 (insertions, deletions, filename) = file.split("\t")
279 hsh[:total][:insertions] += insertions.to_i
280 hsh[:total][:deletions] += deletions.to_i
281 hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
282 hsh[:total][:files] += 1
283 hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
289 # compares the index and the working directory
292 command_lines('diff-files').each do |line|
293 (info, file) = line.split("\t")
294 (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
295 hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest,
296 :sha_file => sha_src, :sha_index => sha_dest, :type => type}
301 # compares the index and the repository
302 def diff_index(treeish)
304 command_lines('diff-index', treeish).each do |line|
305 (info, file) = line.split("\t")
306 (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
307 hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest,
308 :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
315 command_lines('ls-files', '--stage').each do |line|
316 (info, file) = line.split("\t")
317 (mode, sha, stage) = info.split
318 hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
324 def config_remote(name)
326 config_list.each do |key, value|
327 if /remote.#{name}/.match(key)
328 hsh[key.gsub("remote.#{name}.", '')] = value
337 #command('config', ['--get', name])
342 config.merge!(parse_config('~/.gitconfig'))
343 config.merge!(parse_config(File.join(@git_dir, 'config')))
345 #command_lines('config', ['--list']).each do |line|
346 # (key, value) = line.split('=')
352 def parse_config(file)
354 file = File.expand_path(file)
356 current_section = nil
357 File.readlines(file).each do |line|
358 if m = /\[(\w+)\]/.match(line)
359 current_section = m[1]
360 elsif m = /\[(\w+?) "(.*?)"\]/.match(line)
361 current_section = "#{m[1]}.#{m[2]}"
362 elsif m = /(\w+?) = (.*)/.match(line)
363 key = "#{current_section}.#{m[1]}"
373 def config_set(name, value)
374 command('config', [name, "'#{value}'"])
378 path = path.join(' ') if path.is_a?(Array)
382 def remove(path = '.', opts = {})
383 path = path.join(' ') if path.is_a?(Array)
385 arr_opts = ['-f'] # overrides the up-to-date check by default
386 arr_opts << ['-r'] if opts[:recursive]
389 command('rm', arr_opts)
392 def commit(message, opts = {})
393 arr_opts = ["-m '#{message}'"]
394 arr_opts << '-a' if opts[:add_all]
395 command('commit', arr_opts)
398 def reset(commit, opts = {})
400 arr_opts << '--hard' if opts[:hard]
401 arr_opts << commit.to_s if commit
402 command('reset', arr_opts)
406 def branch_new(branch)
407 command('branch', branch)
410 def branch_delete(branch)
411 command('branch', ['-d', branch])
414 def checkout(branch, opts = {})
416 arr_opts << '-f' if opts[:force]
417 arr_opts << branch.to_s
419 command('checkout', arr_opts)
422 def merge(branch, message = nil)
424 arr_opts << ["-m '#{message}'"] if message
425 arr_opts << branch.to_a.join(' ')
426 command('merge', arr_opts)
431 command_lines('diff', ["--cached"]).each do |line|
432 unmerged << $1 if line =~ /^\* Unmerged path (.*)/
437 def conflicts #yields :file, :your, :their
438 self.unmerged.each do |f|
439 your = Tempfile.new("YOUR-#{File.basename(f)}").path
440 arr_opts = [":2:#{f}", ">#{your}"]
441 command('show', arr_opts)
443 their = Tempfile.new("THEIR-#{File.basename(f)}").path
444 arr_opts = [":3:#{f}", ">#{their}"]
445 command('show', arr_opts)
446 yield(f, your, their)
450 def remote_add(name, url, opts = {})
452 arr_opts << '-f' if opts[:with_fetch]
456 command('remote', arr_opts)
459 # this is documented as such, but seems broken for some reason
460 # i'll try to get around it some other way later
461 def remote_remove(name)
462 command('remote', ['rm', name])
466 command_lines('remote')
470 tag_dir = File.join(@git_dir, 'refs', 'tags')
472 Dir.chdir(tag_dir) { tags = Dir.glob('*') }
474 #command_lines('tag')
483 command('fetch', remote.to_s)
486 def push(remote, branch = 'master')
487 command('push', [remote.to_s, branch.to_s])
490 def tag_sha(tag_name)
491 head = File.join(@git_dir, 'refs', 'tags', tag_name)
492 return File.read(head).chomp if File.exists?(head)
494 command('show-ref', ['--tags', '-s', tag_name])
498 command('repack', ['-a', '-d'])
501 # reads a tree into the current index file
502 def read_tree(treeish, opts = {})
504 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
505 arr_opts << treeish.to_a.join(' ')
506 command('read-tree', arr_opts)
510 command('write-tree')
513 def commit_tree(tree, opts = {})
514 opts[:message] = "commit tree #{tree}" if !opts[:message]
515 t = Tempfile.new('commit-message') do |t|
516 t.write(opts[:message])
521 arr_opts << "-p #{opts[:parent]}" if opts[:parent]
522 opts[:parents].each { |p| arr_opts << "-p #{p.to_s}" } if opts[:parents]
523 arr_opts << "< #{t.path}"
524 command('commit-tree', arr_opts)
527 def update_ref(branch, commit)
528 command('update-ref', [branch.to_s, commit.to_s])
531 def checkout_index(opts = {})
533 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
534 arr_opts << "--force" if opts[:force]
535 arr_opts << "--all" if opts[:all]
536 arr_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
537 command('checkout-index', arr_opts)
540 # creates an archive file
547 def archive(sha, file = nil, opts = {})
548 opts[:format] = 'zip' if !opts[:format]
550 if opts[:format] == 'tgz'
551 opts[:format] = 'tar'
552 opts[:add_gzip] = true
556 file = Tempfile.new('archive').path
560 arr_opts << "--format=#{opts[:format]}" if opts[:format]
561 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
562 arr_opts << "--remote=#{opts[:remote]}" if opts[:remote]
564 arr_opts << opts[:path] if opts[:path]
565 arr_opts << '| gzip' if opts[:add_gzip]
566 arr_opts << "> #{file.to_s}"
567 command('archive', arr_opts)
573 def command_lines(cmd, opts = [], chdir = true)
574 command(cmd, opts, chdir).split("\n")
577 def command(cmd, opts = [], chdir = true)
578 ENV['GIT_DIR'] = @git_dir if (@git_dir != ENV['GIT_DIR'])
579 ENV['GIT_INDEX_FILE'] = @git_index_file if (@git_index_file != ENV['GIT_INDEX_FILE'])
580 ENV['GIT_WORK_TREE'] = @git_work_dir if (@git_work_dir != ENV['GIT_WORK_TREE'])
581 path = @git_work_dir || @git_dir || @path
583 opts = opts.to_a.join(' ')
584 git_cmd = "git #{cmd} #{opts}"
587 if chdir && (Dir.getwd != path)
588 Dir.chdir(path) { out = `#{git_cmd} 2>&1`.chomp }
590 out = `#{git_cmd} 2>&1`.chomp
594 @logger.info(git_cmd)
599 if $?.exitstatus == 1 && out == ''
602 raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s)