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
93 command('rev-parse', string)
97 command('name-rev', string).split[1]
101 command('cat-file', ['-t', sha])
105 command('cat-file', ['-s', sha]).to_i
108 # returns useful array of raw commit object data
111 cdata = command_lines('cat-file', ['commit', sha])
112 process_commit_data(cdata, sha)
115 def process_commit_data(data, sha = nil)
119 hsh = {'sha' => sha, 'message' => '', 'parent' => []}
125 if in_message && line != ''
126 hsh['message'] += line + "\n"
129 if (line != '') && !in_message
132 value = data.join(' ')
135 hsh_array << hsh if hsh
136 hsh = {'sha' => sha, 'message' => '', 'parent' => []}
143 elsif in_message && line == ''
151 hsh_array << hsh if hsh
158 def object_contents(sha)
159 command('cat-file', ['-p', sha])
163 data = {'blob' => {}, 'tree' => {}}
164 command_lines('ls-tree', sha.to_s).each do |line|
165 (info, filenm) = line.split("\t")
166 (mode, type, sha) = info.split
167 data[type][filenm] = {:mode => mode, :sha => sha}
174 command_lines('branch', '-a').each do |b|
176 current = true if b[0, 2] == '* '
177 arr << [b.gsub('* ', '').strip, current]
183 branches_all.select { |b| b[1] }.first[0] rescue nil
188 # [tree-ish] = [[line_no, match], [line_no, match2]]
189 # [tree-ish] = [[line_no, match], [line_no, match2]]
190 def grep(string, opts = {})
191 opts[:object] = 'HEAD' if !opts[:object]
194 grep_opts << '-i' if opts[:ignore_case]
195 grep_opts << '-v' if opts[:invert_match]
196 grep_opts << "-e '#{string}'"
197 grep_opts << opts[:object] if opts[:object].is_a?(String)
198 grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
200 command_lines('grep', grep_opts).each do |line|
201 if m = /(.*)\:(\d+)\:(.*)/.match(line)
203 hsh[m[1]] << [m[2].to_i, m[3]]
209 def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
212 diff_opts << obj2 if obj2.is_a?(String)
213 diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
215 command('diff', diff_opts)
218 def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
219 diff_opts = ['--numstat']
221 diff_opts << obj2 if obj2.is_a?(String)
222 diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
224 hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
226 command_lines('diff', diff_opts).each do |file|
227 (insertions, deletions, filename) = file.split("\t")
228 hsh[:total][:insertions] += insertions.to_i
229 hsh[:total][:deletions] += deletions.to_i
230 hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
231 hsh[:total][:files] += 1
232 hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
238 # compares the index and the working directory
241 command_lines('diff-files').each do |line|
242 (info, file) = line.split("\t")
243 (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
244 hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest,
245 :sha_file => sha_src, :sha_index => sha_dest, :type => type}
250 # compares the index and the repository
251 def diff_index(treeish)
253 command_lines('diff-index', treeish).each do |line|
254 (info, file) = line.split("\t")
255 (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
256 hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest,
257 :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
264 command_lines('ls-files', '--stage').each do |line|
265 (info, file) = line.split("\t")
266 (mode, sha, stage) = info.split
267 hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
273 def config_remote(name)
275 command_lines('config', ['--get-regexp', "remote.#{name}"]).each do |line|
276 (key, value) = line.split
277 hsh[key.gsub("remote.#{name}.", '')] = value
283 command('config', ['--get', name])
288 command_lines('config', ['--list']).each do |line|
289 (key, value) = line.split('=')
297 def config_set(name, value)
298 command('config', [name, "'#{value}'"])
302 path = path.join(' ') if path.is_a?(Array)
306 def remove(path = '.', opts = {})
307 path = path.join(' ') if path.is_a?(Array)
309 arr_opts = ['-f'] # overrides the up-to-date check by default
310 arr_opts << ['-r'] if opts[:recursive]
313 command('rm', arr_opts)
316 def commit(message, opts = {})
317 arr_opts = ["-m '#{message}'"]
318 arr_opts << '-a' if opts[:add_all]
319 command('commit', arr_opts)
322 def reset(commit, opts = {})
324 arr_opts << '--hard' if opts[:hard]
325 arr_opts << commit.to_s if commit
326 command('reset', arr_opts)
330 def branch_new(branch)
331 command('branch', branch)
334 def branch_delete(branch)
335 command('branch', ['-d', branch])
338 def checkout(branch, opts = {})
340 arr_opts << '-f' if opts[:force]
341 arr_opts << branch.to_s
343 command('checkout', arr_opts)
346 def merge(branch, message = nil)
348 arr_opts << ["-m '#{message}'"] if message
349 arr_opts << branch.to_a.join(' ')
350 command('merge', arr_opts)
353 def remote_add(name, url, opts = {})
355 arr_opts << '-f' if opts[:with_fetch]
359 command('remote', arr_opts)
362 # this is documented as such, but seems broken for some reason
363 # i'll try to get around it some other way later
364 def remote_remove(name)
365 command('remote', ['rm', name])
369 command_lines('remote')
382 command('fetch', remote.to_s)
385 def push(remote, branch = 'master')
386 command('push', [remote.to_s, branch.to_s])
389 def tag_sha(tag_name)
390 command('show-ref', ['--tags', '-s', tag_name])
394 command('repack', ['-a', '-d'])
397 # reads a tree into the current index file
398 def read_tree(treeish, opts = {})
400 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
401 arr_opts << treeish.to_a.join(' ')
402 command('read-tree', arr_opts)
406 command('write-tree')
409 def commit_tree(tree, opts = {})
410 opts[:message] = "commit tree #{tree}" if !opts[:message]
411 t = Tempfile.new('commit-message') do |t|
412 t.write(opts[:message])
417 arr_opts << "-p #{opts[:parent]}" if opts[:parent]
418 opts[:parents].each { |p| arr_opts << "-p #{p.to_s}" } if opts[:parents]
419 arr_opts << "< #{t.path}"
420 command('commit-tree', arr_opts)
423 def update_ref(branch, commit)
424 command('update-ref', [branch.to_s, commit.to_s])
427 def checkout_index(opts = {})
429 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
430 arr_opts << "--force" if opts[:force]
431 arr_opts << "--all" if opts[:all]
432 arr_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
433 command('checkout-index', arr_opts)
436 # creates an archive file
443 def archive(sha, file = nil, opts = {})
444 opts[:format] = 'zip' if !opts[:format]
446 if opts[:format] == 'tgz'
447 opts[:format] = 'tar'
448 opts[:add_gzip] = true
452 file = Tempfile.new('archive').path
456 arr_opts << "--format=#{opts[:format]}" if opts[:format]
457 arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
458 arr_opts << "--remote=#{opts[:remote]}" if opts[:remote]
460 arr_opts << opts[:path] if opts[:path]
461 arr_opts << '| gzip' if opts[:add_gzip]
462 arr_opts << "> #{file.to_s}"
463 command('archive', arr_opts)
469 def command_lines(cmd, opts = {}, chdir = true)
470 command(cmd, opts, chdir).split("\n")
473 def command(cmd, opts = {}, chdir = true)
474 ENV['GIT_DIR'] = @git_dir if (@git_dir != ENV['GIT_DIR'])
475 ENV['GIT_INDEX_FILE'] = @git_index_file if (@git_index_file != ENV['GIT_INDEX_FILE'])
476 ENV['GIT_WORK_TREE'] = @git_work_dir if (@git_work_dir != ENV['GIT_WORK_TREE'])
477 path = @git_work_dir || @git_dir || @path
479 opts = opts.to_a.join(' ')
480 git_cmd = "git #{cmd} #{opts}"
483 if chdir && (Dir.getwd != path)
484 Dir.chdir(path) { out = `git #{cmd} #{opts} 2>&1`.chomp }
486 out = `git #{cmd} #{opts} 2>&1`.chomp
490 @logger.info(git_cmd)
495 if $?.exitstatus == 1 && out == ''
498 raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s)