120d9ceaffbee913172f26101bd304cc19fcf8ce
[rubygit.git] / lib / git / lib.rb
blob120d9ceaffbee913172f26101bd304cc19fcf8ce
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))
187     end
189     def ls_tree(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}
195       end
196       data
197     end
199     def branches_all
200       head = File.read(File.join(@git_dir, 'HEAD'))
201       arr = []
202       
203       if m = /ref: refs\/heads\/(.*)/.match(head)
204         current = m[1]
205       end
206       arr += list_files('heads').map { |f| [f, f == current] }
207       arr += list_files('remotes').map { |f| [f, false] }
208       
209       #command_lines('branch', '-a').each do |b| 
210       #  current = false
211       #  current = true if b[0, 2] == '* '
212       #  arr << [b.gsub('* ', '').strip, current]
213       #end
214       
215       arr
216     end
218     def list_files(ref_dir)
219       dir = File.join(@git_dir, 'refs', ref_dir)
220       files = nil
221       Dir.chdir(dir) { files = Dir.glob('**/*').select { |f| File.file?(f) } }
222       files
223     end
224     
225     def branch_current
226       branches_all.select { |b| b[1] }.first[0] rescue nil
227     end
230     # returns hash
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]
236       grep_opts = ['-n']
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
242       hsh = {}
243       command_lines('grep', grep_opts).each do |line|
244         if m = /(.*)\:(\d+)\:(.*)/.match(line)        
245           hsh[m[1]] ||= []
246           hsh[m[1]] << [m[2].to_i, m[3]] 
247         end
248       end
249       hsh
250     end
251     
252     def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
253       diff_opts = ['-p']
254       diff_opts << obj1
255       diff_opts << obj2 if obj2.is_a?(String)
256       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
257       
258       command('diff', diff_opts)
259     end
260     
261     def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
262       diff_opts = ['--numstat']
263       diff_opts << obj1
264       diff_opts << obj2 if obj2.is_a?(String)
265       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
266       
267       hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
268       
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}
276       end
277             
278       hsh
279     end
281     # compares the index and the working directory
282     def diff_files
283       hsh = {}
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}
289       end
290       hsh
291     end
292     
293     # compares the index and the repository
294     def diff_index(treeish)
295       hsh = {}
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}
301       end
302       hsh
303     end
304             
305     def ls_files
306       hsh = {}
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}
311       end
312       hsh
313     end
316     def config_remote(name)
317       hsh = {}
318       config_list.each do |key, value|
319         if /remote.#{name}/.match(key)
320           hsh[key.gsub("remote.#{name}.", '')] = value
321         end
322       end
323       hsh
324     end
326     def config_get(name)
327       c = config_list
328       c[name]
329       #command('config', ['--get', name])
330     end
331     
332     def config_list
333       config = {}
334       config.merge!(parse_config('~/.gitconfig'))
335       config.merge!(parse_config(File.join(@git_dir, 'config')))
336       #hsh = {}
337       #command_lines('config', ['--list']).each do |line|
338       #  (key, value) = line.split('=')
339       #  hsh[key] = value
340       #end
341       #hsh
342     end
343     
344     def parse_config(file)
345       hsh = {}
346       file = File.expand_path(file)
347       if File.file?(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]}"
356             hsh[key] = m[2] 
357           end
358         end
359       end
360       hsh
361     end
362     
363     ## WRITE COMMANDS ##
364         
365     def config_set(name, value)
366       command('config', [name, "'#{value}'"])
367     end
368           
369     def add(path = '.')
370       path = path.join(' ') if path.is_a?(Array)
371       command('add', path)
372     end
373     
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]
379       arr_opts << path
381       command('rm', arr_opts)
382     end
384     def commit(message, opts = {})
385       arr_opts = ["-m '#{message}'"]
386       arr_opts << '-a' if opts[:add_all]
387       command('commit', arr_opts)
388     end
390     def reset(commit, opts = {})
391       arr_opts = []
392       arr_opts << '--hard' if opts[:hard]
393       arr_opts << commit.to_s if commit
394       command('reset', arr_opts)
395     end
398     def branch_new(branch)
399       command('branch', branch)
400     end
401     
402     def branch_delete(branch)
403       command('branch', ['-d', branch])
404     end
405     
406     def checkout(branch, opts = {})
407       arr_opts = []
408       arr_opts << '-f' if opts[:force]
409       arr_opts << branch.to_s
410       
411       command('checkout', arr_opts)
412     end
413     
414     def merge(branch, message = nil)      
415       arr_opts = []
416       arr_opts << ["-m '#{message}'"] if message
417       arr_opts << branch.to_a.join(' ')
418       command('merge', arr_opts)
419     end
420     
421     def remote_add(name, url, opts = {})
422       arr_opts = ['add']
423       arr_opts << '-f' if opts[:with_fetch]
424       arr_opts << name
425       arr_opts << url
426       
427       command('remote', arr_opts)
428     end
429     
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])
434     end
435     
436     def remotes
437       command_lines('remote')
438     end
440     def tags
441       tag_dir = File.join(@git_dir, 'refs', 'tags')
442       tags = []
443       Dir.chdir(tag_dir) { tags = Dir.glob('*') }
444       return tags
445       #command_lines('tag')
446     end
448     def tag(tag)
449       command('tag', tag)
450     end
452     
453     def fetch(remote)
454       command('fetch', remote.to_s)
455     end
456     
457     def push(remote, branch = 'master')
458       command('push', [remote.to_s, branch.to_s])
459     end
460     
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)
464       
465       command('show-ref',  ['--tags', '-s', tag_name])
466     end  
467     
468     def repack
469       command('repack', ['-a', '-d'])
470     end
471     
472     # reads a tree into the current index file
473     def read_tree(treeish, opts = {})
474       arr_opts = []
475       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
476       arr_opts << treeish.to_a.join(' ')
477       command('read-tree', arr_opts)
478     end
479     
480     def write_tree
481       command('write-tree')
482     end
483     
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])
488       end
489       
490       arr_opts = []
491       arr_opts << tree
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)
496     end
497     
498     def update_ref(branch, commit)
499       command('update-ref', [branch.to_s, commit.to_s])
500     end
501     
502     def checkout_index(opts = {})
503       arr_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)
509     end
510     
511     # creates an archive file
512     #
513     # options
514     #  :format  (zip, tar)
515     #  :prefix
516     #  :remote
517     #  :path
518     def archive(sha, file = nil, opts = {})
519       opts[:format] = 'zip' if !opts[:format]
520       
521       if opts[:format] == 'tgz'
522         opts[:format] = 'tar' 
523         opts[:add_gzip] = true
524       end
525       
526       if !file
527         file = Tempfile.new('archive').path
528       end
529       
530       arr_opts = []
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]
534       arr_opts << sha
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)
539       return file
540     end
541     
542     private
543     
544     def command_lines(cmd, opts = {}, chdir = true)
545       command(cmd, opts, chdir).split("\n")
546     end
547     
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}"
557       out = nil
558       if chdir && (Dir.getwd != path)
559         Dir.chdir(path) { out = `git #{cmd} #{opts} 2>&1`.chomp } 
560       else
561         out = `git #{cmd} #{opts} 2>&1`.chomp
562       end
563       
564       if @logger
565         @logger.info(git_cmd)
566         @logger.debug(out)
567       end
568             
569       if $?.exitstatus > 0
570         if $?.exitstatus == 1 && out == ''
571           return ''
572         end
573         raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s) 
574       end
575       out
576     end
577     
578   end