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)).chomp
190 data = {'blob' => {}, 'tree' => {}}
192 get_raw_repo.object(revparse(sha)).entry.each do |e|
193 data[e.format_type][e.name] = {:mode => e.format_mode, :sha => e.sha1}
196 #command_lines('ls-tree', sha.to_s).each do |line|
197 # (info, filenm) = line.split("\t")
198 # (mode, type, sha) = info.split
199 # data[type][filenm] = {:mode => mode, :sha => sha}
206 head = File.read(File.join(@git_dir, 'HEAD'))
209 if m = /ref: refs\/heads\/(.*)/.match(head)
212 arr += list_files('heads').map { |f| [f, f == current] }
213 arr += list_files('remotes').map { |f| [f, false] }
215 #command_lines('branch', '-a').each do |b|
217 # current = true if b[0, 2] == '* '
218 # arr << [b.gsub('* ', '').strip, current]
224 def list_files(ref_dir)
225 dir = File.join(@git_dir, 'refs', ref_dir)
227 Dir.chdir(dir) { files = Dir.glob('**/*').select { |f| File.file?(f) } }
232 branches_all.select { |b| b[1] }.first[0] rescue nil
237 # [tree-ish] = [[line_no, match], [line_no, match2]]
238 # [tree-ish] = [[line_no, match], [line_no, match2]]
239 def grep(string, opts = {})
240 opts[:object] = 'HEAD' if !opts[:object]
243 grep_opts << '-i' if opts[:ignore_case]
244 grep_opts << '-v' if opts[:invert_match]
245 grep_opts << "-e '#{string}'"
246 grep_opts << opts[:object] if opts[:object].is_a?(String)
247 grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
249 command_lines('grep', grep_opts).each do |line|
250 if m = /(.*)\:(\d+)\:(.*)/.match(line)
252 hsh[m[1]] << [m[2].to_i, m[3]]
258 def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
261 diff_opts << obj2 if obj2.is_a?(String)
262 diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
264 command('diff', diff_opts)
267 def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
268 diff_opts = ['--numstat']
270 diff_opts << obj2 if obj2.is_a?(String)
271 diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
273 hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
275 command_lines('diff', diff_opts).each do |file|
276 (insertions, deletions, filename) = file.split("\t")
277 hsh[:total][:insertions] += insertions.to_i
278 hsh[:total][:deletions] += deletions.to_i
279 hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
280 hsh[:total][:files] += 1
281 hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
287 # compares the index and the working directory
290 command_lines('diff-files').each do |line|
291 (info, file) = line.split("\t")
292 (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
293 hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest,
294 :sha_file => sha_src, :sha_index => sha_dest, :type => type}
299 # compares the index and the repository
300 def diff_index(treeish)
302 command_lines('diff-index', treeish).each do |line|
303 (info, file) = line.split("\t")
304 (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
305 hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest,
306 :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
313 command_lines('ls-files', '--stage').each do |line|
314 (info, file) = line.split("\t")
315 (mode, sha, stage) = info.split
316 hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
322 def config_remote(name)
324 config_list.each do |key, value|
325 if /remote.#{name}/.match(key)
326 hsh[key.gsub("remote.#{name}.", '')] = value
335 #command('config', ['--get', name])
340 config.merge!(parse_config('~/.gitconfig'))
341 config.merge!(parse_config(File.join(@git_dir, 'config')))
343 #command_lines('config', ['--list']).each do |line|
344 # (key, value) = line.split('=')
350 def parse_config(file)
352 file = File.expand_path(file)
354 current_section = nil
355 File.readlines(file).each do |line|
356 if m = /\[(\w+)\]/.match(line)
357 current_section = m[1]
358 elsif m = /\[(\w+?) "(.*?)"\]/.match(line)
359 current_section = "#{m[1]}.#{m[2]}"
360 elsif m = /(\w+?) = (.*)/.match(line)
361 key = "#{current_section}.#{m[1]}"
371 def config_set(name, value)
372 command('config', [name, "'#{value}'"])
376 path = path.join(' ') if path.is_a?(Array)
380 def remove(path = '.', opts = {})
381 path = path.join(' ') if path.is_a?(Array)
383 arr_opts = ['-f'] # overrides the up-to-date check by default
384 arr_opts << ['-r'] if opts[:recursive]
387 command('rm', arr_opts)
390 def commit(message, opts = {})
391 arr_opts = ["-m '#{message}'"]
392 arr_opts << '-a' if opts[:add_all]
393 command('commit', arr_opts)
396 def reset(commit, opts = {})
398 arr_opts << '--hard' if opts[:hard]
399 arr_opts << commit.to_s if commit
400 command('reset', arr_opts)
404 def branch_new(branch)
405 command('branch', branch)
408 def branch_delete(branch)
409 command('branch', ['-d', branch])
412 def checkout(branch, opts = {})
414 arr_opts << '-f' if opts[:force]
415 arr_opts << branch.to_s
417 command('checkout', arr_opts)
420 def merge(branch, message = nil)
422 arr_opts << ["-m '#{message}'"] if message
423 arr_opts << branch.to_a.join(' ')
424 command('merge', arr_opts)
427 def remote_add(name, url, opts = {})
429 arr_opts << '-f' if opts[:with_fetch]
433 command('remote', arr_opts)
436 # this is documented as such, but seems broken for some reason
437 # i'll try to get around it some other way later
438 def remote_remove(name)
439 command('remote', ['rm', name])
443 command_lines('remote')
447 tag_dir = File.join(@git_dir, 'refs', 'tags')
449 Dir.chdir(tag_dir) { tags = Dir.glob('*') }
451 #command_lines('tag')
460 command('fetch', remote.to_s)
463 def push(remote, branch = 'master')
464 command('push', [remote.to_s, branch.to_s])
467 def tag_sha(tag_name)
468 head = File.join(@git_dir, 'refs', 'tags', tag_name)
469 return File.read(head).chomp if File.exists?(head)
471 command('show-ref', ['--tags', '-s', tag_name])
475 command('repack', ['-a', '-d'])
478 # reads a tree into the current index file
479 def read_tree(treeish, opts = {})
481 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
482 arr_opts << treeish.to_a.join(' ')
483 command('read-tree', arr_opts)
487 command('write-tree')
490 def commit_tree(tree, opts = {})
491 opts[:message] = "commit tree #{tree}" if !opts[:message]
492 t = Tempfile.new('commit-message') do |t|
493 t.write(opts[:message])
498 arr_opts << "-p #{opts[:parent]}" if opts[:parent]
499 opts[:parents].each { |p| arr_opts << "-p #{p.to_s}" } if opts[:parents]
500 arr_opts << "< #{t.path}"
501 command('commit-tree', arr_opts)
504 def update_ref(branch, commit)
505 command('update-ref', [branch.to_s, commit.to_s])
508 def checkout_index(opts = {})
510 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
511 arr_opts << "--force" if opts[:force]
512 arr_opts << "--all" if opts[:all]
513 arr_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
514 command('checkout-index', arr_opts)
517 # creates an archive file
524 def archive(sha, file = nil, opts = {})
525 opts[:format] = 'zip' if !opts[:format]
527 if opts[:format] == 'tgz'
528 opts[:format] = 'tar'
529 opts[:add_gzip] = true
533 file = Tempfile.new('archive').path
537 arr_opts << "--format=#{opts[:format]}" if opts[:format]
538 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
539 arr_opts << "--remote=#{opts[:remote]}" if opts[:remote]
541 arr_opts << opts[:path] if opts[:path]
542 arr_opts << '| gzip' if opts[:add_gzip]
543 arr_opts << "> #{file.to_s}"
544 command('archive', arr_opts)
550 def command_lines(cmd, opts = {}, chdir = true)
551 command(cmd, opts, chdir).split("\n")
554 def command(cmd, opts = {}, chdir = true)
555 ENV['GIT_DIR'] = @git_dir if (@git_dir != ENV['GIT_DIR'])
556 ENV['GIT_INDEX_FILE'] = @git_index_file if (@git_index_file != ENV['GIT_INDEX_FILE'])
557 ENV['GIT_WORK_TREE'] = @git_work_dir if (@git_work_dir != ENV['GIT_WORK_TREE'])
558 path = @git_work_dir || @git_dir || @path
560 opts = opts.to_a.join(' ')
561 git_cmd = "git #{cmd} #{opts}"
564 if chdir && (Dir.getwd != path)
565 Dir.chdir(path) { out = `git #{cmd} #{opts} 2>&1`.chomp }
567 out = `git #{cmd} #{opts} 2>&1`.chomp
571 @logger.info(git_cmd)
576 if $?.exitstatus == 1 && out == ''
579 raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s)