5 class GitExecuteError < StandardError
17 def initialize(base = nil, logger = nil)
18 if base.is_a?(Git::Base)
19 @git_dir = base.repo.path
20 @git_index_file = base.index.path if base.index
21 @git_work_dir = base.dir.path if base.dir
22 elsif base.is_a?(Hash)
23 @git_dir = base[:repository]
24 @git_index_file = base[:index]
25 @git_work_dir = base[:working_directory]
36 # tries to clone the given repo
38 # returns {:repository} (if bare)
39 # {:working_directory} otherwise
42 # :remote - name of remote (rather than 'origin')
43 # :bare - no working directory
45 # TODO - make this work with SSH password or auth_key
47 def clone(repository, name, opts = {})
48 @path = opts[:path] || '.'
49 opts[:path] ? clone_dir = File.join(@path, name) : clone_dir = name
52 arr_opts << "--bare" if opts[:bare]
53 arr_opts << "-o #{opts[:remote]}" if opts[:remote]
54 arr_opts << repository
57 command('clone', arr_opts)
59 opts[:bare] ? {:repository => clone_dir} : {:working_directory => clone_dir}
66 def log_commits(opts = {})
67 arr_opts = ['--pretty=oneline']
68 arr_opts << "-#{opts[:count]}" if opts[:count]
69 arr_opts << "--since=\"#{opts[:since]}\"" if opts[:since].is_a? String
70 arr_opts << "#{opts[:between][0].to_s}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2)
71 arr_opts << opts[:object] if opts[:object].is_a? String
72 arr_opts << '-- ' + opts[:path_limiter] if opts[:path_limiter].is_a? String
74 command_lines('log', arr_opts, true).map { |l| l.split.first }
77 def full_log_commits(opts = {})
78 arr_opts = ['--pretty=raw']
79 arr_opts << "-#{opts[:count]}" if opts[:count]
80 arr_opts << "--since=\"#{opts[:since]}\"" if opts[:since].is_a? String
81 arr_opts << "#{opts[:between][0].to_s}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2)
82 arr_opts << opts[:object] if opts[:object].is_a? String
83 arr_opts << '-- ' + opts[:path_limiter] if opts[:path_limiter].is_a? String
85 full_log = command_lines('log', arr_opts, true)
86 process_commit_data(full_log)
90 if /\w{40}/.match(string) # passing in a sha - just no-op it
94 head = File.join(@git_dir, 'refs', 'heads', string)
95 return File.read(head) if File.file?(head)
97 head = File.join(@git_dir, 'refs', 'remotes', string)
98 return File.read(head) if File.file?(head)
100 command('rev-parse', string)
104 command('name-rev', string).split[1]
108 command('cat-file', ['-t', sha])
112 command('cat-file', ['-s', sha]).to_i
115 # returns useful array of raw commit object data
118 cdata = command_lines('cat-file', ['commit', sha])
119 process_commit_data(cdata, sha)
122 def process_commit_data(data, sha = nil)
126 hsh = {'sha' => sha, 'message' => '', 'parent' => []}
132 if in_message && line != ''
133 hsh['message'] += line + "\n"
136 if (line != '') && !in_message
139 value = data.join(' ')
142 hsh_array << hsh if hsh
143 hsh = {'sha' => sha, 'message' => '', 'parent' => []}
150 elsif in_message && line == ''
158 hsh_array << hsh if hsh
165 def object_contents(sha)
166 command('cat-file', ['-p', sha])
170 data = {'blob' => {}, 'tree' => {}}
171 command_lines('ls-tree', sha.to_s).each do |line|
172 (info, filenm) = line.split("\t")
173 (mode, type, sha) = info.split
174 data[type][filenm] = {:mode => mode, :sha => sha}
180 head = File.read(File.join(@git_dir, 'HEAD'))
183 if m = /ref: refs\/heads\/(.*)/.match(head)
186 arr += list_files('heads').map { |f| [f, f == current] }
187 arr += list_files('remotes').map { |f| [f, false] }
189 #command_lines('branch', '-a').each do |b|
191 # current = true if b[0, 2] == '* '
192 # arr << [b.gsub('* ', '').strip, current]
198 def list_files(ref_dir)
199 dir = File.join(@git_dir, 'refs', ref_dir)
201 Dir.chdir(dir) { files = Dir.glob('**/*').select { |f| File.file?(f) } }
206 branches_all.select { |b| b[1] }.first[0] rescue nil
211 # [tree-ish] = [[line_no, match], [line_no, match2]]
212 # [tree-ish] = [[line_no, match], [line_no, match2]]
213 def grep(string, opts = {})
214 opts[:object] = 'HEAD' if !opts[:object]
217 grep_opts << '-i' if opts[:ignore_case]
218 grep_opts << '-v' if opts[:invert_match]
219 grep_opts << "-e '#{string}'"
220 grep_opts << opts[:object] if opts[:object].is_a?(String)
221 grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
223 command_lines('grep', grep_opts).each do |line|
224 if m = /(.*)\:(\d+)\:(.*)/.match(line)
226 hsh[m[1]] << [m[2].to_i, m[3]]
232 def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
235 diff_opts << obj2 if obj2.is_a?(String)
236 diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
238 command('diff', diff_opts)
241 def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
242 diff_opts = ['--numstat']
244 diff_opts << obj2 if obj2.is_a?(String)
245 diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
247 hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
249 command_lines('diff', diff_opts).each do |file|
250 (insertions, deletions, filename) = file.split("\t")
251 hsh[:total][:insertions] += insertions.to_i
252 hsh[:total][:deletions] += deletions.to_i
253 hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
254 hsh[:total][:files] += 1
255 hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
261 # compares the index and the working directory
264 command_lines('diff-files').each do |line|
265 (info, file) = line.split("\t")
266 (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
267 hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest,
268 :sha_file => sha_src, :sha_index => sha_dest, :type => type}
273 # compares the index and the repository
274 def diff_index(treeish)
276 command_lines('diff-index', treeish).each do |line|
277 (info, file) = line.split("\t")
278 (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
279 hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest,
280 :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
287 command_lines('ls-files', '--stage').each do |line|
288 (info, file) = line.split("\t")
289 (mode, sha, stage) = info.split
290 hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
296 def config_remote(name)
298 command_lines('config', ['--get-regexp', "remote.#{name}"]).each do |line|
299 (key, value) = line.split
300 hsh[key.gsub("remote.#{name}.", '')] = value
308 #command('config', ['--get', name])
313 config.merge!(parse_config('~/.gitconfig'))
314 config.merge!(parse_config(File.join(@git_dir, 'config')))
316 #command_lines('config', ['--list']).each do |line|
317 # (key, value) = line.split('=')
323 def parse_config(file)
325 file = File.expand_path(file)
327 current_section = nil
328 File.readlines(file).each do |line|
329 if m = /\[(\w+)\]/.match(line)
330 current_section = m[1]
331 elsif m = /\[(\w+?) "(.*?)"\]/.match(line)
332 current_section = "#{m[1]}.#{m[2]}"
333 elsif m = /(\w+?) = (.*)/.match(line)
334 key = "#{current_section}.#{m[1]}"
344 def config_set(name, value)
345 command('config', [name, "'#{value}'"])
349 path = path.join(' ') if path.is_a?(Array)
353 def remove(path = '.', opts = {})
354 path = path.join(' ') if path.is_a?(Array)
356 arr_opts = ['-f'] # overrides the up-to-date check by default
357 arr_opts << ['-r'] if opts[:recursive]
360 command('rm', arr_opts)
363 def commit(message, opts = {})
364 arr_opts = ["-m '#{message}'"]
365 arr_opts << '-a' if opts[:add_all]
366 command('commit', arr_opts)
369 def reset(commit, opts = {})
371 arr_opts << '--hard' if opts[:hard]
372 arr_opts << commit.to_s if commit
373 command('reset', arr_opts)
377 def branch_new(branch)
378 command('branch', branch)
381 def branch_delete(branch)
382 command('branch', ['-d', branch])
385 def checkout(branch, opts = {})
387 arr_opts << '-f' if opts[:force]
388 arr_opts << branch.to_s
390 command('checkout', arr_opts)
393 def merge(branch, message = nil)
395 arr_opts << ["-m '#{message}'"] if message
396 arr_opts << branch.to_a.join(' ')
397 command('merge', arr_opts)
400 def remote_add(name, url, opts = {})
402 arr_opts << '-f' if opts[:with_fetch]
406 command('remote', arr_opts)
409 # this is documented as such, but seems broken for some reason
410 # i'll try to get around it some other way later
411 def remote_remove(name)
412 command('remote', ['rm', name])
416 command_lines('remote')
420 tag_dir = File.join(@git_dir, 'refs', 'tags')
422 Dir.chdir(tag_dir) { tags = Dir.glob('*') }
424 #command_lines('tag')
433 command('fetch', remote.to_s)
436 def push(remote, branch = 'master')
437 command('push', [remote.to_s, branch.to_s])
440 def tag_sha(tag_name)
441 head = File.join(@git_dir, 'refs', 'tags', tag_name)
442 return File.read(head).chomp if File.exists?(head)
444 command('show-ref', ['--tags', '-s', tag_name])
448 command('repack', ['-a', '-d'])
451 # reads a tree into the current index file
452 def read_tree(treeish, opts = {})
454 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
455 arr_opts << treeish.to_a.join(' ')
456 command('read-tree', arr_opts)
460 command('write-tree')
463 def commit_tree(tree, opts = {})
464 opts[:message] = "commit tree #{tree}" if !opts[:message]
465 t = Tempfile.new('commit-message') do |t|
466 t.write(opts[:message])
471 arr_opts << "-p #{opts[:parent]}" if opts[:parent]
472 opts[:parents].each { |p| arr_opts << "-p #{p.to_s}" } if opts[:parents]
473 arr_opts << "< #{t.path}"
474 command('commit-tree', arr_opts)
477 def update_ref(branch, commit)
478 command('update-ref', [branch.to_s, commit.to_s])
481 def checkout_index(opts = {})
483 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
484 arr_opts << "--force" if opts[:force]
485 arr_opts << "--all" if opts[:all]
486 arr_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
487 command('checkout-index', arr_opts)
490 # creates an archive file
497 def archive(sha, file = nil, opts = {})
498 opts[:format] = 'zip' if !opts[:format]
500 if opts[:format] == 'tgz'
501 opts[:format] = 'tar'
502 opts[:add_gzip] = true
506 file = Tempfile.new('archive').path
510 arr_opts << "--format=#{opts[:format]}" if opts[:format]
511 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
512 arr_opts << "--remote=#{opts[:remote]}" if opts[:remote]
514 arr_opts << opts[:path] if opts[:path]
515 arr_opts << '| gzip' if opts[:add_gzip]
516 arr_opts << "> #{file.to_s}"
517 command('archive', arr_opts)
523 def command_lines(cmd, opts = {}, chdir = true)
524 command(cmd, opts, chdir).split("\n")
527 def command(cmd, opts = {}, chdir = true)
528 ENV['GIT_DIR'] = @git_dir if (@git_dir != ENV['GIT_DIR'])
529 ENV['GIT_INDEX_FILE'] = @git_index_file if (@git_index_file != ENV['GIT_INDEX_FILE'])
530 ENV['GIT_WORK_TREE'] = @git_work_dir if (@git_work_dir != ENV['GIT_WORK_TREE'])
531 path = @git_work_dir || @git_dir || @path
533 opts = opts.to_a.join(' ')
534 git_cmd = "git #{cmd} #{opts}"
537 if chdir && (Dir.getwd != path)
538 Dir.chdir(path) { out = `git #{cmd} #{opts} 2>&1`.chomp }
540 out = `git #{cmd} #{opts} 2>&1`.chomp
544 @logger.info(git_cmd)
549 if $?.exitstatus == 1 && out == ''
552 raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s)