cd24fca4ecaf5121dc955c813582e4ade2769fff
[rubygit.git] / lib / git / lib.rb
blobcd24fca4ecaf5121dc955c813582e4ade2769fff
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         if /\w{40}/.match(sha)  # valid sha
85           repo = get_raw_repo
86           return process_commit_data(repo.log(sha, count))
87         end
88       end
89       
90       arr_opts = ['--pretty=raw']
91       arr_opts << "-#{opts[:count]}" if opts[:count]
92       arr_opts << "--since=\"#{opts[:since]}\"" if opts[:since].is_a? String
93       arr_opts << "#{opts[:between][0].to_s}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2)
94       arr_opts << opts[:object] if opts[:object].is_a? String
95       arr_opts << '-- ' + opts[:path_limiter] if opts[:path_limiter].is_a? String
96       
97       full_log = command_lines('log', arr_opts, true)
98       process_commit_data(full_log)
99     end
100     
101     def revparse(string)
102       if /\w{40}/.match(string)  # passing in a sha - just no-op it
103         return string
104       end
105             
106       head = File.join(@git_dir, 'refs', 'heads', string)
107       return File.read(head).chomp if File.file?(head)
109       head = File.join(@git_dir, 'refs', 'remotes', string)
110       return File.read(head).chomp if File.file?(head)
111       
112       head = File.join(@git_dir, 'refs', 'tags', string)
113       return File.read(head).chomp if File.file?(head)
114       
115       command('rev-parse', string)
116     end
117     
118     def namerev(string)
119       command('name-rev', string).split[1]
120     end
121     
122     def object_type(sha)
123       command('cat-file', ['-t', sha])
124     end
125     
126     def object_size(sha)
127       command('cat-file', ['-s', sha]).to_i
128     end
130     def get_raw_repo
131       @raw_repo ||= Git::Raw::Repository.new(@git_dir)
132     end
133     
134     # returns useful array of raw commit object data
135     def commit_data(sha)
136       sha = sha.to_s
137       cdata = get_raw_repo.cat_file(revparse(sha))
138       #cdata = command_lines('cat-file', ['commit', sha])
139       process_commit_data(cdata, sha)
140     end
141     
142     def process_commit_data(data, sha = nil)
143       in_message = false
144             
145       if sha
146         hsh = {'sha' => sha, 'message' => '', 'parent' => []}
147       else
148         hsh_array = []        
149       end
150     
151       data.each do |line|
152         line = line.chomp
153         if in_message && line != ''
154           hsh['message'] += line + "\n"
155         end
157         if (line != '') && !in_message
158           data = line.split
159           key = data.shift
160           value = data.join(' ')
161           if key == 'commit'
162             sha = value
163             hsh_array << hsh if hsh
164             hsh = {'sha' => sha, 'message' => '', 'parent' => []}
165           end
166           if key == 'parent'
167             hsh[key] << value
168           else
169             hsh[key] = value
170           end
171         elsif in_message && line == ''
172           in_message = false
173         else
174           in_message = true
175         end
176       end
177       
178       if hsh_array
179         hsh_array << hsh if hsh
180         hsh_array
181       else
182         hsh
183       end
184     end
185     
186     def object_contents(sha)
187       #command('cat-file', ['-p', sha])
188       get_raw_repo.cat_file(revparse(sha)).chomp
189     end
191     def ls_tree(sha)
192       data = {'blob' => {}, 'tree' => {}}
193       
194       get_raw_repo.object(revparse(sha)).entry.each do |e|
195         data[e.format_type][e.name] = {:mode => e.format_mode, :sha => e.sha1}
196       end
197         
198       #command_lines('ls-tree', sha.to_s).each do |line|
199       #  (info, filenm) = line.split("\t")
200       #  (mode, type, sha) = info.split
201       #  data[type][filenm] = {:mode => mode, :sha => sha}
202       #end
203       
204       data
205     end
207     def branches_all
208       head = File.read(File.join(@git_dir, 'HEAD'))
209       arr = []
210       
211       if m = /ref: refs\/heads\/(.*)/.match(head)
212         current = m[1]
213       end
214       arr += list_files('heads').map { |f| [f, f == current] }
215       arr += list_files('remotes').map { |f| [f, false] }
216       
217       #command_lines('branch', '-a').each do |b| 
218       #  current = false
219       #  current = true if b[0, 2] == '* '
220       #  arr << [b.gsub('* ', '').strip, current]
221       #end
222       
223       arr
224     end
226     def list_files(ref_dir)
227       dir = File.join(@git_dir, 'refs', ref_dir)
228       files = nil
229       Dir.chdir(dir) { files = Dir.glob('**/*').select { |f| File.file?(f) } }
230       files
231     end
232     
233     def branch_current
234       branches_all.select { |b| b[1] }.first[0] rescue nil
235     end
238     # returns hash
239     # [tree-ish] = [[line_no, match], [line_no, match2]]
240     # [tree-ish] = [[line_no, match], [line_no, match2]]
241     def grep(string, opts = {})
242       opts[:object] = 'HEAD' if !opts[:object]
244       grep_opts = ['-n']
245       grep_opts << '-i' if opts[:ignore_case]
246       grep_opts << '-v' if opts[:invert_match]
247       grep_opts << "-e '#{string}'"
248       grep_opts << opts[:object] if opts[:object].is_a?(String)
249       grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
250       hsh = {}
251       command_lines('grep', grep_opts).each do |line|
252         if m = /(.*)\:(\d+)\:(.*)/.match(line)        
253           hsh[m[1]] ||= []
254           hsh[m[1]] << [m[2].to_i, m[3]] 
255         end
256       end
257       hsh
258     end
259     
260     def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
261       diff_opts = ['-p']
262       diff_opts << obj1
263       diff_opts << obj2 if obj2.is_a?(String)
264       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
265       
266       command('diff', diff_opts)
267     end
268     
269     def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
270       diff_opts = ['--numstat']
271       diff_opts << obj1
272       diff_opts << obj2 if obj2.is_a?(String)
273       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
274       
275       hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
276       
277       command_lines('diff', diff_opts).each do |file|
278         (insertions, deletions, filename) = file.split("\t")
279         hsh[:total][:insertions] += insertions.to_i
280         hsh[:total][:deletions] += deletions.to_i
281         hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
282         hsh[:total][:files] += 1
283         hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
284       end
285             
286       hsh
287     end
289     # compares the index and the working directory
290     def diff_files
291       hsh = {}
292       command_lines('diff-files').each do |line|
293         (info, file) = line.split("\t")
294         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
295         hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest, 
296                       :sha_file => sha_src, :sha_index => sha_dest, :type => type}
297       end
298       hsh
299     end
300     
301     # compares the index and the repository
302     def diff_index(treeish)
303       hsh = {}
304       command_lines('diff-index', treeish).each do |line|
305         (info, file) = line.split("\t")
306         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
307         hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest, 
308                       :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
309       end
310       hsh
311     end
312             
313     def ls_files
314       hsh = {}
315       command_lines('ls-files', '--stage').each do |line|
316         (info, file) = line.split("\t")
317         (mode, sha, stage) = info.split
318         hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
319       end
320       hsh
321     end
324     def config_remote(name)
325       hsh = {}
326       config_list.each do |key, value|
327         if /remote.#{name}/.match(key)
328           hsh[key.gsub("remote.#{name}.", '')] = value
329         end
330       end
331       hsh
332     end
334     def config_get(name)
335       c = config_list
336       c[name]
337       #command('config', ['--get', name])
338     end
339     
340     def config_list
341       config = {}
342       config.merge!(parse_config('~/.gitconfig'))
343       config.merge!(parse_config(File.join(@git_dir, 'config')))
344       #hsh = {}
345       #command_lines('config', ['--list']).each do |line|
346       #  (key, value) = line.split('=')
347       #  hsh[key] = value
348       #end
349       #hsh
350     end
351     
352     def parse_config(file)
353       hsh = {}
354       file = File.expand_path(file)
355       if File.file?(file)
356         current_section = nil
357         File.readlines(file).each do |line|
358           if m = /\[(\w+)\]/.match(line)
359             current_section = m[1]
360           elsif m = /\[(\w+?) "(.*?)"\]/.match(line)
361             current_section = "#{m[1]}.#{m[2]}"
362           elsif m = /(\w+?) = (.*)/.match(line)
363             key = "#{current_section}.#{m[1]}"
364             hsh[key] = m[2] 
365           end
366         end
367       end
368       hsh
369     end
370     
371     ## WRITE COMMANDS ##
372         
373     def config_set(name, value)
374       command('config', [name, "'#{value}'"])
375     end
376           
377     def add(path = '.')
378       path = path.join(' ') if path.is_a?(Array)
379       command('add', path)
380     end
381     
382     def remove(path = '.', opts = {})
383       path = path.join(' ') if path.is_a?(Array)
385       arr_opts = ['-f']  # overrides the up-to-date check by default
386       arr_opts << ['-r'] if opts[:recursive]
387       arr_opts << path
389       command('rm', arr_opts)
390     end
392     def commit(message, opts = {})
393       arr_opts = ["-m '#{message}'"]
394       arr_opts << '-a' if opts[:add_all]
395       command('commit', arr_opts)
396     end
398     def reset(commit, opts = {})
399       arr_opts = []
400       arr_opts << '--hard' if opts[:hard]
401       arr_opts << commit.to_s if commit
402       command('reset', arr_opts)
403     end
406     def branch_new(branch)
407       command('branch', branch)
408     end
409     
410     def branch_delete(branch)
411       command('branch', ['-d', branch])
412     end
413     
414     def checkout(branch, opts = {})
415       arr_opts = []
416       arr_opts << '-f' if opts[:force]
417       arr_opts << branch.to_s
418       
419       command('checkout', arr_opts)
420     end
421     
422     def merge(branch, message = nil)      
423       arr_opts = []
424       arr_opts << ["-m '#{message}'"] if message
425       arr_opts << branch.to_a.join(' ')
426       command('merge', arr_opts)
427     end
428     
429     def remote_add(name, url, opts = {})
430       arr_opts = ['add']
431       arr_opts << '-f' if opts[:with_fetch]
432       arr_opts << name
433       arr_opts << url
434       
435       command('remote', arr_opts)
436     end
437     
438     # this is documented as such, but seems broken for some reason
439     # i'll try to get around it some other way later
440     def remote_remove(name)
441       command('remote', ['rm', name])
442     end
443     
444     def remotes
445       command_lines('remote')
446     end
448     def tags
449       tag_dir = File.join(@git_dir, 'refs', 'tags')
450       tags = []
451       Dir.chdir(tag_dir) { tags = Dir.glob('*') }
452       return tags
453       #command_lines('tag')
454     end
456     def tag(tag)
457       command('tag', tag)
458     end
460     
461     def fetch(remote)
462       command('fetch', remote.to_s)
463     end
464     
465     def push(remote, branch = 'master')
466       command('push', [remote.to_s, branch.to_s])
467     end
468     
469     def tag_sha(tag_name)
470       head = File.join(@git_dir, 'refs', 'tags', tag_name)
471       return File.read(head).chomp if File.exists?(head)
472       
473       command('show-ref',  ['--tags', '-s', tag_name])
474     end  
475     
476     def repack
477       command('repack', ['-a', '-d'])
478     end
479     
480     # reads a tree into the current index file
481     def read_tree(treeish, opts = {})
482       arr_opts = []
483       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
484       arr_opts << treeish.to_a.join(' ')
485       command('read-tree', arr_opts)
486     end
487     
488     def write_tree
489       command('write-tree')
490     end
491     
492     def commit_tree(tree, opts = {})
493       opts[:message] = "commit tree #{tree}" if !opts[:message]
494       t = Tempfile.new('commit-message') do |t|
495         t.write(opts[:message])
496       end
497       
498       arr_opts = []
499       arr_opts << tree
500       arr_opts << "-p #{opts[:parent]}" if opts[:parent]
501       opts[:parents].each { |p| arr_opts << "-p #{p.to_s}" } if opts[:parents]
502       arr_opts << "< #{t.path}"
503       command('commit-tree', arr_opts)
504     end
505     
506     def update_ref(branch, commit)
507       command('update-ref', [branch.to_s, commit.to_s])
508     end
509     
510     def checkout_index(opts = {})
511       arr_opts = []
512       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
513       arr_opts << "--force" if opts[:force]
514       arr_opts << "--all" if opts[:all]
515       arr_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
516       command('checkout-index', arr_opts)
517     end
518     
519     # creates an archive file
520     #
521     # options
522     #  :format  (zip, tar)
523     #  :prefix
524     #  :remote
525     #  :path
526     def archive(sha, file = nil, opts = {})
527       opts[:format] = 'zip' if !opts[:format]
528       
529       if opts[:format] == 'tgz'
530         opts[:format] = 'tar' 
531         opts[:add_gzip] = true
532       end
533       
534       if !file
535         file = Tempfile.new('archive').path
536       end
537       
538       arr_opts = []
539       arr_opts << "--format=#{opts[:format]}" if opts[:format]
540       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
541       arr_opts << "--remote=#{opts[:remote]}" if opts[:remote]
542       arr_opts << sha
543       arr_opts << opts[:path] if opts[:path]
544       arr_opts << '| gzip' if opts[:add_gzip]
545       arr_opts << "> #{file.to_s}"
546       command('archive', arr_opts)
547       return file
548     end
549     
550     private
551     
552     def command_lines(cmd, opts = {}, chdir = true)
553       command(cmd, opts, chdir).split("\n")
554     end
555     
556     def command(cmd, opts = {}, chdir = true)
557       ENV['GIT_DIR'] = @git_dir if (@git_dir != ENV['GIT_DIR'])
558       ENV['GIT_INDEX_FILE'] = @git_index_file if (@git_index_file != ENV['GIT_INDEX_FILE'])
559       ENV['GIT_WORK_TREE'] = @git_work_dir if (@git_work_dir != ENV['GIT_WORK_TREE'])
560       path = @git_work_dir || @git_dir || @path
562       opts = opts.to_a.join(' ')
563       git_cmd = "git #{cmd} #{opts}"
565       out = nil
566       if chdir && (Dir.getwd != path)
567         Dir.chdir(path) { out = `git #{cmd} #{opts} 2>&1`.chomp } 
568       else
569         out = `git #{cmd} #{opts} 2>&1`.chomp
570       end
571       
572       if @logger
573         @logger.info(git_cmd)
574         @logger.debug(out)
575       end
576             
577       if $?.exitstatus > 0
578         if $?.exitstatus == 1 && out == ''
579           return ''
580         end
581         raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s) 
582       end
583       out
584     end
585     
586   end