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
85 return process_commit_data(repo.log(sha, count))
88 arr_opts = ['--pretty=raw']
89 arr_opts << "-#{opts[:count]}" if opts[:count]
90 arr_opts << "--since=\"#{opts[:since]}\"" if opts[:since].is_a? String
91 arr_opts << "#{opts[:between][0].to_s}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2)
92 arr_opts << opts[:object] if opts[:object].is_a? String
93 arr_opts << '-- ' + opts[:path_limiter] if opts[:path_limiter].is_a? String
95 full_log = command_lines('log', arr_opts, true)
96 process_commit_data(full_log)
100 if /\w{40}/.match(string) # passing in a sha - just no-op it
104 head = File.join(@git_dir, 'refs', 'heads', string)
105 return File.read(head).chomp if File.file?(head)
107 head = File.join(@git_dir, 'refs', 'remotes', string)
108 return File.read(head).chomp if File.file?(head)
110 head = File.join(@git_dir, 'refs', 'tags', string)
111 return File.read(head).chomp if File.file?(head)
113 command('rev-parse', string)
117 command('name-rev', string).split[1]
121 command('cat-file', ['-t', sha])
125 command('cat-file', ['-s', sha]).to_i
129 @raw_repo ||= Git::Raw::Repository.new(@git_dir)
132 # returns useful array of raw commit object data
135 cdata = get_raw_repo.cat_file(revparse(sha))
136 #cdata = command_lines('cat-file', ['commit', sha])
137 process_commit_data(cdata, sha)
140 def process_commit_data(data, sha = nil)
144 hsh = {'sha' => sha, 'message' => '', 'parent' => []}
151 if in_message && line != ''
152 hsh['message'] += line + "\n"
155 if (line != '') && !in_message
158 value = data.join(' ')
161 hsh_array << hsh if hsh
162 hsh = {'sha' => sha, 'message' => '', 'parent' => []}
169 elsif in_message && line == ''
177 hsh_array << hsh if hsh
184 def object_contents(sha)
185 #command('cat-file', ['-p', sha])
186 get_raw_repo.cat_file(revparse(sha))
190 data = {'blob' => {}, 'tree' => {}}
191 command_lines('ls-tree', sha.to_s).each do |line|
192 (info, filenm) = line.split("\t")
193 (mode, type, sha) = info.split
194 data[type][filenm] = {:mode => mode, :sha => sha}
200 head = File.read(File.join(@git_dir, 'HEAD'))
203 if m = /ref: refs\/heads\/(.*)/.match(head)
206 arr += list_files('heads').map { |f| [f, f == current] }
207 arr += list_files('remotes').map { |f| [f, false] }
209 #command_lines('branch', '-a').each do |b|
211 # current = true if b[0, 2] == '* '
212 # arr << [b.gsub('* ', '').strip, current]
218 def list_files(ref_dir)
219 dir = File.join(@git_dir, 'refs', ref_dir)
221 Dir.chdir(dir) { files = Dir.glob('**/*').select { |f| File.file?(f) } }
226 branches_all.select { |b| b[1] }.first[0] rescue nil
231 # [tree-ish] = [[line_no, match], [line_no, match2]]
232 # [tree-ish] = [[line_no, match], [line_no, match2]]
233 def grep(string, opts = {})
234 opts[:object] = 'HEAD' if !opts[:object]
237 grep_opts << '-i' if opts[:ignore_case]
238 grep_opts << '-v' if opts[:invert_match]
239 grep_opts << "-e '#{string}'"
240 grep_opts << opts[:object] if opts[:object].is_a?(String)
241 grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
243 command_lines('grep', grep_opts).each do |line|
244 if m = /(.*)\:(\d+)\:(.*)/.match(line)
246 hsh[m[1]] << [m[2].to_i, m[3]]
252 def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
255 diff_opts << obj2 if obj2.is_a?(String)
256 diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
258 command('diff', diff_opts)
261 def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
262 diff_opts = ['--numstat']
264 diff_opts << obj2 if obj2.is_a?(String)
265 diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
267 hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
269 command_lines('diff', diff_opts).each do |file|
270 (insertions, deletions, filename) = file.split("\t")
271 hsh[:total][:insertions] += insertions.to_i
272 hsh[:total][:deletions] += deletions.to_i
273 hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
274 hsh[:total][:files] += 1
275 hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
281 # compares the index and the working directory
284 command_lines('diff-files').each do |line|
285 (info, file) = line.split("\t")
286 (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
287 hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest,
288 :sha_file => sha_src, :sha_index => sha_dest, :type => type}
293 # compares the index and the repository
294 def diff_index(treeish)
296 command_lines('diff-index', treeish).each do |line|
297 (info, file) = line.split("\t")
298 (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
299 hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest,
300 :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
307 command_lines('ls-files', '--stage').each do |line|
308 (info, file) = line.split("\t")
309 (mode, sha, stage) = info.split
310 hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
316 def config_remote(name)
318 config_list.each do |key, value|
319 if /remote.#{name}/.match(key)
320 hsh[key.gsub("remote.#{name}.", '')] = value
329 #command('config', ['--get', name])
334 config.merge!(parse_config('~/.gitconfig'))
335 config.merge!(parse_config(File.join(@git_dir, 'config')))
337 #command_lines('config', ['--list']).each do |line|
338 # (key, value) = line.split('=')
344 def parse_config(file)
346 file = File.expand_path(file)
348 current_section = nil
349 File.readlines(file).each do |line|
350 if m = /\[(\w+)\]/.match(line)
351 current_section = m[1]
352 elsif m = /\[(\w+?) "(.*?)"\]/.match(line)
353 current_section = "#{m[1]}.#{m[2]}"
354 elsif m = /(\w+?) = (.*)/.match(line)
355 key = "#{current_section}.#{m[1]}"
365 def config_set(name, value)
366 command('config', [name, "'#{value}'"])
370 path = path.join(' ') if path.is_a?(Array)
374 def remove(path = '.', opts = {})
375 path = path.join(' ') if path.is_a?(Array)
377 arr_opts = ['-f'] # overrides the up-to-date check by default
378 arr_opts << ['-r'] if opts[:recursive]
381 command('rm', arr_opts)
384 def commit(message, opts = {})
385 arr_opts = ["-m '#{message}'"]
386 arr_opts << '-a' if opts[:add_all]
387 command('commit', arr_opts)
390 def reset(commit, opts = {})
392 arr_opts << '--hard' if opts[:hard]
393 arr_opts << commit.to_s if commit
394 command('reset', arr_opts)
398 def branch_new(branch)
399 command('branch', branch)
402 def branch_delete(branch)
403 command('branch', ['-d', branch])
406 def checkout(branch, opts = {})
408 arr_opts << '-f' if opts[:force]
409 arr_opts << branch.to_s
411 command('checkout', arr_opts)
414 def merge(branch, message = nil)
416 arr_opts << ["-m '#{message}'"] if message
417 arr_opts << branch.to_a.join(' ')
418 command('merge', arr_opts)
421 def remote_add(name, url, opts = {})
423 arr_opts << '-f' if opts[:with_fetch]
427 command('remote', arr_opts)
430 # this is documented as such, but seems broken for some reason
431 # i'll try to get around it some other way later
432 def remote_remove(name)
433 command('remote', ['rm', name])
437 command_lines('remote')
441 tag_dir = File.join(@git_dir, 'refs', 'tags')
443 Dir.chdir(tag_dir) { tags = Dir.glob('*') }
445 #command_lines('tag')
454 command('fetch', remote.to_s)
457 def push(remote, branch = 'master')
458 command('push', [remote.to_s, branch.to_s])
461 def tag_sha(tag_name)
462 head = File.join(@git_dir, 'refs', 'tags', tag_name)
463 return File.read(head).chomp if File.exists?(head)
465 command('show-ref', ['--tags', '-s', tag_name])
469 command('repack', ['-a', '-d'])
472 # reads a tree into the current index file
473 def read_tree(treeish, opts = {})
475 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
476 arr_opts << treeish.to_a.join(' ')
477 command('read-tree', arr_opts)
481 command('write-tree')
484 def commit_tree(tree, opts = {})
485 opts[:message] = "commit tree #{tree}" if !opts[:message]
486 t = Tempfile.new('commit-message') do |t|
487 t.write(opts[:message])
492 arr_opts << "-p #{opts[:parent]}" if opts[:parent]
493 opts[:parents].each { |p| arr_opts << "-p #{p.to_s}" } if opts[:parents]
494 arr_opts << "< #{t.path}"
495 command('commit-tree', arr_opts)
498 def update_ref(branch, commit)
499 command('update-ref', [branch.to_s, commit.to_s])
502 def checkout_index(opts = {})
504 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
505 arr_opts << "--force" if opts[:force]
506 arr_opts << "--all" if opts[:all]
507 arr_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
508 command('checkout-index', arr_opts)
511 # creates an archive file
518 def archive(sha, file = nil, opts = {})
519 opts[:format] = 'zip' if !opts[:format]
521 if opts[:format] == 'tgz'
522 opts[:format] = 'tar'
523 opts[:add_gzip] = true
527 file = Tempfile.new('archive').path
531 arr_opts << "--format=#{opts[:format]}" if opts[:format]
532 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
533 arr_opts << "--remote=#{opts[:remote]}" if opts[:remote]
535 arr_opts << opts[:path] if opts[:path]
536 arr_opts << '| gzip' if opts[:add_gzip]
537 arr_opts << "> #{file.to_s}"
538 command('archive', arr_opts)
544 def command_lines(cmd, opts = {}, chdir = true)
545 command(cmd, opts, chdir).split("\n")
548 def command(cmd, opts = {}, chdir = true)
549 ENV['GIT_DIR'] = @git_dir if (@git_dir != ENV['GIT_DIR'])
550 ENV['GIT_INDEX_FILE'] = @git_index_file if (@git_index_file != ENV['GIT_INDEX_FILE'])
551 ENV['GIT_WORK_TREE'] = @git_work_dir if (@git_work_dir != ENV['GIT_WORK_TREE'])
552 path = @git_work_dir || @git_dir || @path
554 opts = opts.to_a.join(' ')
555 git_cmd = "git #{cmd} #{opts}"
558 if chdir && (Dir.getwd != path)
559 Dir.chdir(path) { out = `git #{cmd} #{opts} 2>&1`.chomp }
561 out = `git #{cmd} #{opts} 2>&1`.chomp
565 @logger.info(git_cmd)
570 if $?.exitstatus == 1 && out == ''
573 raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s)