got log and cat-file moved to pure ruby
[rubygit.git] / lib / git / lib.rb
blob9c6a0414776109f7c0474dab9013830f7815b1e9
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 = Git::Raw::Repository.new(@git_dir)
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     end
188     def ls_tree(sha)
189       data = {'blob' => {}, 'tree' => {}}
190       command_lines('ls-tree', sha.to_s).each do |line|
191         (info, filenm) = line.split("\t")
192         (mode, type, sha) = info.split
193         data[type][filenm] = {:mode => mode, :sha => sha}
194       end
195       data
196     end
198     def branches_all
199       head = File.read(File.join(@git_dir, 'HEAD'))
200       arr = []
201       
202       if m = /ref: refs\/heads\/(.*)/.match(head)
203         current = m[1]
204       end
205       arr += list_files('heads').map { |f| [f, f == current] }
206       arr += list_files('remotes').map { |f| [f, false] }
207       
208       #command_lines('branch', '-a').each do |b| 
209       #  current = false
210       #  current = true if b[0, 2] == '* '
211       #  arr << [b.gsub('* ', '').strip, current]
212       #end
213       
214       arr
215     end
217     def list_files(ref_dir)
218       dir = File.join(@git_dir, 'refs', ref_dir)
219       files = nil
220       Dir.chdir(dir) { files = Dir.glob('**/*').select { |f| File.file?(f) } }
221       files
222     end
223     
224     def branch_current
225       branches_all.select { |b| b[1] }.first[0] rescue nil
226     end
229     # returns hash
230     # [tree-ish] = [[line_no, match], [line_no, match2]]
231     # [tree-ish] = [[line_no, match], [line_no, match2]]
232     def grep(string, opts = {})
233       opts[:object] = 'HEAD' if !opts[:object]
235       grep_opts = ['-n']
236       grep_opts << '-i' if opts[:ignore_case]
237       grep_opts << '-v' if opts[:invert_match]
238       grep_opts << "-e '#{string}'"
239       grep_opts << opts[:object] if opts[:object].is_a?(String)
240       grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
241       hsh = {}
242       command_lines('grep', grep_opts).each do |line|
243         if m = /(.*)\:(\d+)\:(.*)/.match(line)        
244           hsh[m[1]] ||= []
245           hsh[m[1]] << [m[2].to_i, m[3]] 
246         end
247       end
248       hsh
249     end
250     
251     def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
252       diff_opts = ['-p']
253       diff_opts << obj1
254       diff_opts << obj2 if obj2.is_a?(String)
255       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
256       
257       command('diff', diff_opts)
258     end
259     
260     def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
261       diff_opts = ['--numstat']
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       hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
267       
268       command_lines('diff', diff_opts).each do |file|
269         (insertions, deletions, filename) = file.split("\t")
270         hsh[:total][:insertions] += insertions.to_i
271         hsh[:total][:deletions] += deletions.to_i
272         hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
273         hsh[:total][:files] += 1
274         hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
275       end
276             
277       hsh
278     end
280     # compares the index and the working directory
281     def diff_files
282       hsh = {}
283       command_lines('diff-files').each do |line|
284         (info, file) = line.split("\t")
285         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
286         hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest, 
287                       :sha_file => sha_src, :sha_index => sha_dest, :type => type}
288       end
289       hsh
290     end
291     
292     # compares the index and the repository
293     def diff_index(treeish)
294       hsh = {}
295       command_lines('diff-index', treeish).each do |line|
296         (info, file) = line.split("\t")
297         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
298         hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest, 
299                       :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
300       end
301       hsh
302     end
303             
304     def ls_files
305       hsh = {}
306       command_lines('ls-files', '--stage').each do |line|
307         (info, file) = line.split("\t")
308         (mode, sha, stage) = info.split
309         hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
310       end
311       hsh
312     end
315     def config_remote(name)
316       hsh = {}
317       config_list.each do |key, value|
318         if /remote.#{name}/.match(key)
319           hsh[key.gsub("remote.#{name}.", '')] = value
320         end
321       end
322       hsh
323     end
325     def config_get(name)
326       c = config_list
327       c[name]
328       #command('config', ['--get', name])
329     end
330     
331     def config_list
332       config = {}
333       config.merge!(parse_config('~/.gitconfig'))
334       config.merge!(parse_config(File.join(@git_dir, 'config')))
335       #hsh = {}
336       #command_lines('config', ['--list']).each do |line|
337       #  (key, value) = line.split('=')
338       #  hsh[key] = value
339       #end
340       #hsh
341     end
342     
343     def parse_config(file)
344       hsh = {}
345       file = File.expand_path(file)
346       if File.file?(file)
347         current_section = nil
348         File.readlines(file).each do |line|
349           if m = /\[(\w+)\]/.match(line)
350             current_section = m[1]
351           elsif m = /\[(\w+?) "(.*?)"\]/.match(line)
352             current_section = "#{m[1]}.#{m[2]}"
353           elsif m = /(\w+?) = (.*)/.match(line)
354             key = "#{current_section}.#{m[1]}"
355             hsh[key] = m[2] 
356           end
357         end
358       end
359       hsh
360     end
361     
362     ## WRITE COMMANDS ##
363         
364     def config_set(name, value)
365       command('config', [name, "'#{value}'"])
366     end
367           
368     def add(path = '.')
369       path = path.join(' ') if path.is_a?(Array)
370       command('add', path)
371     end
372     
373     def remove(path = '.', opts = {})
374       path = path.join(' ') if path.is_a?(Array)
376       arr_opts = ['-f']  # overrides the up-to-date check by default
377       arr_opts << ['-r'] if opts[:recursive]
378       arr_opts << path
380       command('rm', arr_opts)
381     end
383     def commit(message, opts = {})
384       arr_opts = ["-m '#{message}'"]
385       arr_opts << '-a' if opts[:add_all]
386       command('commit', arr_opts)
387     end
389     def reset(commit, opts = {})
390       arr_opts = []
391       arr_opts << '--hard' if opts[:hard]
392       arr_opts << commit.to_s if commit
393       command('reset', arr_opts)
394     end
397     def branch_new(branch)
398       command('branch', branch)
399     end
400     
401     def branch_delete(branch)
402       command('branch', ['-d', branch])
403     end
404     
405     def checkout(branch, opts = {})
406       arr_opts = []
407       arr_opts << '-f' if opts[:force]
408       arr_opts << branch.to_s
409       
410       command('checkout', arr_opts)
411     end
412     
413     def merge(branch, message = nil)      
414       arr_opts = []
415       arr_opts << ["-m '#{message}'"] if message
416       arr_opts << branch.to_a.join(' ')
417       command('merge', arr_opts)
418     end
419     
420     def remote_add(name, url, opts = {})
421       arr_opts = ['add']
422       arr_opts << '-f' if opts[:with_fetch]
423       arr_opts << name
424       arr_opts << url
425       
426       command('remote', arr_opts)
427     end
428     
429     # this is documented as such, but seems broken for some reason
430     # i'll try to get around it some other way later
431     def remote_remove(name)
432       command('remote', ['rm', name])
433     end
434     
435     def remotes
436       command_lines('remote')
437     end
439     def tags
440       tag_dir = File.join(@git_dir, 'refs', 'tags')
441       tags = []
442       Dir.chdir(tag_dir) { tags = Dir.glob('*') }
443       return tags
444       #command_lines('tag')
445     end
447     def tag(tag)
448       command('tag', tag)
449     end
451     
452     def fetch(remote)
453       command('fetch', remote.to_s)
454     end
455     
456     def push(remote, branch = 'master')
457       command('push', [remote.to_s, branch.to_s])
458     end
459     
460     def tag_sha(tag_name)
461       head = File.join(@git_dir, 'refs', 'tags', tag_name)
462       return File.read(head).chomp if File.exists?(head)
463       
464       command('show-ref',  ['--tags', '-s', tag_name])
465     end  
466     
467     def repack
468       command('repack', ['-a', '-d'])
469     end
470     
471     # reads a tree into the current index file
472     def read_tree(treeish, opts = {})
473       arr_opts = []
474       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
475       arr_opts << treeish.to_a.join(' ')
476       command('read-tree', arr_opts)
477     end
478     
479     def write_tree
480       command('write-tree')
481     end
482     
483     def commit_tree(tree, opts = {})
484       opts[:message] = "commit tree #{tree}" if !opts[:message]
485       t = Tempfile.new('commit-message') do |t|
486         t.write(opts[:message])
487       end
488       
489       arr_opts = []
490       arr_opts << tree
491       arr_opts << "-p #{opts[:parent]}" if opts[:parent]
492       opts[:parents].each { |p| arr_opts << "-p #{p.to_s}" } if opts[:parents]
493       arr_opts << "< #{t.path}"
494       command('commit-tree', arr_opts)
495     end
496     
497     def update_ref(branch, commit)
498       command('update-ref', [branch.to_s, commit.to_s])
499     end
500     
501     def checkout_index(opts = {})
502       arr_opts = []
503       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
504       arr_opts << "--force" if opts[:force]
505       arr_opts << "--all" if opts[:all]
506       arr_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
507       command('checkout-index', arr_opts)
508     end
509     
510     # creates an archive file
511     #
512     # options
513     #  :format  (zip, tar)
514     #  :prefix
515     #  :remote
516     #  :path
517     def archive(sha, file = nil, opts = {})
518       opts[:format] = 'zip' if !opts[:format]
519       
520       if opts[:format] == 'tgz'
521         opts[:format] = 'tar' 
522         opts[:add_gzip] = true
523       end
524       
525       if !file
526         file = Tempfile.new('archive').path
527       end
528       
529       arr_opts = []
530       arr_opts << "--format=#{opts[:format]}" if opts[:format]
531       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
532       arr_opts << "--remote=#{opts[:remote]}" if opts[:remote]
533       arr_opts << sha
534       arr_opts << opts[:path] if opts[:path]
535       arr_opts << '| gzip' if opts[:add_gzip]
536       arr_opts << "> #{file.to_s}"
537       command('archive', arr_opts)
538       return file
539     end
540     
541     private
542     
543     def command_lines(cmd, opts = {}, chdir = true)
544       command(cmd, opts, chdir).split("\n")
545     end
546     
547     def command(cmd, opts = {}, chdir = true)
548       ENV['GIT_DIR'] = @git_dir if (@git_dir != ENV['GIT_DIR'])
549       ENV['GIT_INDEX_FILE'] = @git_index_file if (@git_index_file != ENV['GIT_INDEX_FILE'])
550       ENV['GIT_WORK_TREE'] = @git_work_dir if (@git_work_dir != ENV['GIT_WORK_TREE'])
551       path = @git_work_dir || @git_dir || @path
553       opts = opts.to_a.join(' ')
554       git_cmd = "git #{cmd} #{opts}"
556       out = nil
557       if chdir && (Dir.getwd != path)
558         Dir.chdir(path) { out = `git #{cmd} #{opts} 2>&1`.chomp } 
559       else
560         out = `git #{cmd} #{opts} 2>&1`.chomp
561       end
562       
563       if @logger
564         @logger.info(git_cmd)
565         @logger.debug(out)
566       end
567             
568       if $?.exitstatus > 0
569         if $?.exitstatus == 1 && out == ''
570           return ''
571         end
572         raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s) 
573       end
574       out
575     end
576     
577   end