added Matthias and Simon to credits for the gitrb code
[rubygit.git] / lib / git / lib.rb
blobdecd6d404447b8a9794448f19da8d349c8d8d83d
1 require 'tempfile'
3 module Git
4   
5   class GitExecuteError < StandardError 
6   end
7   
8   class Lib
9       
10     @git_dir = nil
11     @git_index_file = nil
12     @git_work_dir = nil
13     @path = nil
14     
15     @logger = nil
16     @raw_repo = nil
17     
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]
27       end
28       if logger
29         @logger = logger
30       end
31     end
32     
33     def init
34       command('init')
35     end
36     
37     # tries to clone the given repo
38     #
39     # returns {:repository} (if bare)
40     #         {:working_directory} otherwise
41     #
42     # accepts options:
43     #  :remote - name of remote (rather than 'origin')
44     #  :bare   - no working directory
45     # 
46     # TODO - make this work with SSH password or auth_key
47     #
48     def clone(repository, name, opts = {})
49       @path = opts[:path] || '.'
50       opts[:path] ? clone_dir = File.join(@path, name) : clone_dir = name
51       
52       arr_opts = []
53       arr_opts << "--bare" if opts[:bare]
54       arr_opts << "-o #{opts[:remote]}" if opts[:remote]
55       arr_opts << repository
56       arr_opts << clone_dir
57       
58       command('clone', arr_opts)
59       
60       opts[:bare] ? {:repository => clone_dir} : {:working_directory => clone_dir}
61     end
62     
63     
64     ## READ COMMANDS ##
65     
66     
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
74       
75       command_lines('log', arr_opts, true).map { |l| l.split.first }
76     end
77     
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
83         
84         repo = get_raw_repo
85         return process_commit_data(repo.log(sha, count))
86       end
87       
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
94       
95       full_log = command_lines('log', arr_opts, true)
96       process_commit_data(full_log)
97     end
98     
99     def revparse(string)
100       if /\w{40}/.match(string)  # passing in a sha - just no-op it
101         return string
102       end
103             
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)
109       
110       head = File.join(@git_dir, 'refs', 'tags', string)
111       return File.read(head).chomp if File.file?(head)
112       
113       command('rev-parse', string)
114     end
115     
116     def namerev(string)
117       command('name-rev', string).split[1]
118     end
119     
120     def object_type(sha)
121       command('cat-file', ['-t', sha])
122     end
123     
124     def object_size(sha)
125       command('cat-file', ['-s', sha]).to_i
126     end
128     def get_raw_repo
129       @raw_repo ||= Git::Raw::Repository.new(@git_dir)
130     end
131     
132     # returns useful array of raw commit object data
133     def commit_data(sha)
134       sha = sha.to_s
135       cdata = get_raw_repo.cat_file(revparse(sha))
136       #cdata = command_lines('cat-file', ['commit', sha])
137       process_commit_data(cdata, sha)
138     end
139     
140     def process_commit_data(data, sha = nil)
141       in_message = false
142             
143       if sha
144         hsh = {'sha' => sha, 'message' => '', 'parent' => []}
145       else
146         hsh_array = []        
147       end
148     
149       data.each do |line|
150         line = line.chomp
151         if in_message && line != ''
152           hsh['message'] += line + "\n"
153         end
155         if (line != '') && !in_message
156           data = line.split
157           key = data.shift
158           value = data.join(' ')
159           if key == 'commit'
160             sha = value
161             hsh_array << hsh if hsh
162             hsh = {'sha' => sha, 'message' => '', 'parent' => []}
163           end
164           if key == 'parent'
165             hsh[key] << value
166           else
167             hsh[key] = value
168           end
169         elsif in_message && line == ''
170           in_message = false
171         else
172           in_message = true
173         end
174       end
175       
176       if hsh_array
177         hsh_array << hsh if hsh
178         hsh_array
179       else
180         hsh
181       end
182     end
183     
184     def object_contents(sha)
185       #command('cat-file', ['-p', sha])
186       get_raw_repo.cat_file(revparse(sha)).chomp
187     end
189     def ls_tree(sha)
190       data = {'blob' => {}, 'tree' => {}}
191       
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}
194       end
195         
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}
200       #end
201       
202       data
203     end
205     def branches_all
206       head = File.read(File.join(@git_dir, 'HEAD'))
207       arr = []
208       
209       if m = /ref: refs\/heads\/(.*)/.match(head)
210         current = m[1]
211       end
212       arr += list_files('heads').map { |f| [f, f == current] }
213       arr += list_files('remotes').map { |f| [f, false] }
214       
215       #command_lines('branch', '-a').each do |b| 
216       #  current = false
217       #  current = true if b[0, 2] == '* '
218       #  arr << [b.gsub('* ', '').strip, current]
219       #end
220       
221       arr
222     end
224     def list_files(ref_dir)
225       dir = File.join(@git_dir, 'refs', ref_dir)
226       files = nil
227       Dir.chdir(dir) { files = Dir.glob('**/*').select { |f| File.file?(f) } }
228       files
229     end
230     
231     def branch_current
232       branches_all.select { |b| b[1] }.first[0] rescue nil
233     end
236     # returns hash
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]
242       grep_opts = ['-n']
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
248       hsh = {}
249       command_lines('grep', grep_opts).each do |line|
250         if m = /(.*)\:(\d+)\:(.*)/.match(line)        
251           hsh[m[1]] ||= []
252           hsh[m[1]] << [m[2].to_i, m[3]] 
253         end
254       end
255       hsh
256     end
257     
258     def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
259       diff_opts = ['-p']
260       diff_opts << obj1
261       diff_opts << obj2 if obj2.is_a?(String)
262       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
263       
264       command('diff', diff_opts)
265     end
266     
267     def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
268       diff_opts = ['--numstat']
269       diff_opts << obj1
270       diff_opts << obj2 if obj2.is_a?(String)
271       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
272       
273       hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
274       
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}
282       end
283             
284       hsh
285     end
287     # compares the index and the working directory
288     def diff_files
289       hsh = {}
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}
295       end
296       hsh
297     end
298     
299     # compares the index and the repository
300     def diff_index(treeish)
301       hsh = {}
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}
307       end
308       hsh
309     end
310             
311     def ls_files
312       hsh = {}
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}
317       end
318       hsh
319     end
322     def config_remote(name)
323       hsh = {}
324       config_list.each do |key, value|
325         if /remote.#{name}/.match(key)
326           hsh[key.gsub("remote.#{name}.", '')] = value
327         end
328       end
329       hsh
330     end
332     def config_get(name)
333       c = config_list
334       c[name]
335       #command('config', ['--get', name])
336     end
337     
338     def config_list
339       config = {}
340       config.merge!(parse_config('~/.gitconfig'))
341       config.merge!(parse_config(File.join(@git_dir, 'config')))
342       #hsh = {}
343       #command_lines('config', ['--list']).each do |line|
344       #  (key, value) = line.split('=')
345       #  hsh[key] = value
346       #end
347       #hsh
348     end
349     
350     def parse_config(file)
351       hsh = {}
352       file = File.expand_path(file)
353       if File.file?(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]}"
362             hsh[key] = m[2] 
363           end
364         end
365       end
366       hsh
367     end
368     
369     ## WRITE COMMANDS ##
370         
371     def config_set(name, value)
372       command('config', [name, "'#{value}'"])
373     end
374           
375     def add(path = '.')
376       path = path.join(' ') if path.is_a?(Array)
377       command('add', path)
378     end
379     
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]
385       arr_opts << path
387       command('rm', arr_opts)
388     end
390     def commit(message, opts = {})
391       arr_opts = ["-m '#{message}'"]
392       arr_opts << '-a' if opts[:add_all]
393       command('commit', arr_opts)
394     end
396     def reset(commit, opts = {})
397       arr_opts = []
398       arr_opts << '--hard' if opts[:hard]
399       arr_opts << commit.to_s if commit
400       command('reset', arr_opts)
401     end
404     def branch_new(branch)
405       command('branch', branch)
406     end
407     
408     def branch_delete(branch)
409       command('branch', ['-d', branch])
410     end
411     
412     def checkout(branch, opts = {})
413       arr_opts = []
414       arr_opts << '-f' if opts[:force]
415       arr_opts << branch.to_s
416       
417       command('checkout', arr_opts)
418     end
419     
420     def merge(branch, message = nil)      
421       arr_opts = []
422       arr_opts << ["-m '#{message}'"] if message
423       arr_opts << branch.to_a.join(' ')
424       command('merge', arr_opts)
425     end
426     
427     def remote_add(name, url, opts = {})
428       arr_opts = ['add']
429       arr_opts << '-f' if opts[:with_fetch]
430       arr_opts << name
431       arr_opts << url
432       
433       command('remote', arr_opts)
434     end
435     
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])
440     end
441     
442     def remotes
443       command_lines('remote')
444     end
446     def tags
447       tag_dir = File.join(@git_dir, 'refs', 'tags')
448       tags = []
449       Dir.chdir(tag_dir) { tags = Dir.glob('*') }
450       return tags
451       #command_lines('tag')
452     end
454     def tag(tag)
455       command('tag', tag)
456     end
458     
459     def fetch(remote)
460       command('fetch', remote.to_s)
461     end
462     
463     def push(remote, branch = 'master')
464       command('push', [remote.to_s, branch.to_s])
465     end
466     
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)
470       
471       command('show-ref',  ['--tags', '-s', tag_name])
472     end  
473     
474     def repack
475       command('repack', ['-a', '-d'])
476     end
477     
478     # reads a tree into the current index file
479     def read_tree(treeish, opts = {})
480       arr_opts = []
481       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
482       arr_opts << treeish.to_a.join(' ')
483       command('read-tree', arr_opts)
484     end
485     
486     def write_tree
487       command('write-tree')
488     end
489     
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])
494       end
495       
496       arr_opts = []
497       arr_opts << tree
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)
502     end
503     
504     def update_ref(branch, commit)
505       command('update-ref', [branch.to_s, commit.to_s])
506     end
507     
508     def checkout_index(opts = {})
509       arr_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)
515     end
516     
517     # creates an archive file
518     #
519     # options
520     #  :format  (zip, tar)
521     #  :prefix
522     #  :remote
523     #  :path
524     def archive(sha, file = nil, opts = {})
525       opts[:format] = 'zip' if !opts[:format]
526       
527       if opts[:format] == 'tgz'
528         opts[:format] = 'tar' 
529         opts[:add_gzip] = true
530       end
531       
532       if !file
533         file = Tempfile.new('archive').path
534       end
535       
536       arr_opts = []
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]
540       arr_opts << sha
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)
545       return file
546     end
547     
548     private
549     
550     def command_lines(cmd, opts = {}, chdir = true)
551       command(cmd, opts, chdir).split("\n")
552     end
553     
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}"
563       out = nil
564       if chdir && (Dir.getwd != path)
565         Dir.chdir(path) { out = `git #{cmd} #{opts} 2>&1`.chomp } 
566       else
567         out = `git #{cmd} #{opts} 2>&1`.chomp
568       end
569       
570       if @logger
571         @logger.info(git_cmd)
572         @logger.debug(out)
573       end
574             
575       if $?.exitstatus > 0
576         if $?.exitstatus == 1 && out == ''
577           return ''
578         end
579         raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s) 
580       end
581       out
582     end
583     
584   end