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