293e00bd635e65cd097907b451df4dd3c3d1f754
[rubygit.git] / lib / git / lib.rb
blob293e00bd635e65cd097907b451df4dd3c3d1f754
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       command('rev-parse', string)
94     end
95     
96     def namerev(string)
97       command('name-rev', string).split[1]
98     end
99     
100     def object_type(sha)
101       command('cat-file', ['-t', sha])
102     end
103     
104     def object_size(sha)
105       command('cat-file', ['-s', sha]).to_i
106     end
107     
108     # returns useful array of raw commit object data
109     def commit_data(sha)
110       sha = sha.to_s
111       cdata = command_lines('cat-file', ['commit', sha])
112       process_commit_data(cdata, sha)
113     end
114     
115     def process_commit_data(data, sha = nil)
116       in_message = false
117       
118       if sha
119         hsh = {'sha' => sha, 'message' => '', 'parent' => []}
120       else
121         hsh_array = []        
122       end
123     
124       data.each do |line|
125         if in_message && line != ''
126           hsh['message'] += line + "\n"
127         end
129         if (line != '') && !in_message
130           data = line.split
131           key = data.shift
132           value = data.join(' ')
133           if key == 'commit'
134             sha = value
135             hsh_array << hsh if hsh
136             hsh = {'sha' => sha, 'message' => '', 'parent' => []}
137           end
138           if key == 'parent'
139             hsh[key] << value
140           else
141             hsh[key] = value
142           end
143         elsif in_message && line == ''
144           in_message = false
145         else
146           in_message = true
147         end
148       end
149       
150       if hsh_array
151         hsh_array << hsh if hsh
152         hsh_array
153       else
154         hsh
155       end
156     end
157     
158     def object_contents(sha)
159       command('cat-file', ['-p', sha])
160     end
162     def ls_tree(sha)
163       data = {'blob' => {}, 'tree' => {}}
164       command_lines('ls-tree', sha.to_s).each do |line|
165         (info, filenm) = line.split("\t")
166         (mode, type, sha) = info.split
167         data[type][filenm] = {:mode => mode, :sha => sha}
168       end
169       data
170     end
172     def branches_all
173       arr = []
174       command_lines('branch', '-a').each do |b| 
175         current = false
176         current = true if b[0, 2] == '* '
177         arr << [b.gsub('* ', '').strip, current]
178       end
179       arr
180     end
182     def branch_current
183       branches_all.select { |b| b[1] }.first[0] rescue nil
184     end
187     # returns hash
188     # [tree-ish] = [[line_no, match], [line_no, match2]]
189     # [tree-ish] = [[line_no, match], [line_no, match2]]
190     def grep(string, opts = {})
191       opts[:object] = 'HEAD' if !opts[:object]
193       grep_opts = ['-n']
194       grep_opts << '-i' if opts[:ignore_case]
195       grep_opts << '-v' if opts[:invert_match]
196       grep_opts << "-e '#{string}'"
197       grep_opts << opts[:object] if opts[:object].is_a?(String)
198       grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
199       hsh = {}
200       command_lines('grep', grep_opts).each do |line|
201         if m = /(.*)\:(\d+)\:(.*)/.match(line)        
202           hsh[m[1]] ||= []
203           hsh[m[1]] << [m[2].to_i, m[3]] 
204         end
205       end
206       hsh
207     end
208     
209     def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
210       diff_opts = ['-p']
211       diff_opts << obj1
212       diff_opts << obj2 if obj2.is_a?(String)
213       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
214       
215       command('diff', diff_opts)
216     end
217     
218     def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
219       diff_opts = ['--numstat']
220       diff_opts << obj1
221       diff_opts << obj2 if obj2.is_a?(String)
222       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
223       
224       hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
225       
226       command_lines('diff', diff_opts).each do |file|
227         (insertions, deletions, filename) = file.split("\t")
228         hsh[:total][:insertions] += insertions.to_i
229         hsh[:total][:deletions] += deletions.to_i
230         hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
231         hsh[:total][:files] += 1
232         hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
233       end
234             
235       hsh
236     end
238     # compares the index and the working directory
239     def diff_files
240       hsh = {}
241       command_lines('diff-files').each do |line|
242         (info, file) = line.split("\t")
243         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
244         hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest, 
245                       :sha_file => sha_src, :sha_index => sha_dest, :type => type}
246       end
247       hsh
248     end
249     
250     # compares the index and the repository
251     def diff_index(treeish)
252       hsh = {}
253       command_lines('diff-index', treeish).each do |line|
254         (info, file) = line.split("\t")
255         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
256         hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest, 
257                       :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
258       end
259       hsh
260     end
261             
262     def ls_files
263       hsh = {}
264       command_lines('ls-files', '--stage').each do |line|
265         (info, file) = line.split("\t")
266         (mode, sha, stage) = info.split
267         hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
268       end
269       hsh
270     end
273     def config_remote(name)
274       hsh = {}
275       command_lines('config', ['--get-regexp', "remote.#{name}"]).each do |line|
276         (key, value) = line.split
277         hsh[key.gsub("remote.#{name}.", '')] = value
278       end
279       hsh
280     end
282     def config_get(name)
283       command('config', ['--get', name])
284     end
285     
286     def config_list
287       hsh = {}
288       command_lines('config', ['--list']).each do |line|
289         (key, value) = line.split('=')
290         hsh[key] = value
291       end
292       hsh
293     end
294     
295     ## WRITE COMMANDS ##
296         
297     def config_set(name, value)
298       command('config', [name, "'#{value}'"])
299     end
300           
301     def add(path = '.')
302       path = path.join(' ') if path.is_a?(Array)
303       command('add', path)
304     end
305     
306     def remove(path = '.', opts = {})
307       path = path.join(' ') if path.is_a?(Array)
309       arr_opts = ['-f']  # overrides the up-to-date check by default
310       arr_opts << ['-r'] if opts[:recursive]
311       arr_opts << path
313       command('rm', arr_opts)
314     end
316     def commit(message, opts = {})
317       arr_opts = ["-m '#{message}'"]
318       arr_opts << '-a' if opts[:add_all]
319       command('commit', arr_opts)
320     end
322     def reset(commit, opts = {})
323       arr_opts = []
324       arr_opts << '--hard' if opts[:hard]
325       arr_opts << commit.to_s if commit
326       command('reset', arr_opts)
327     end
330     def branch_new(branch)
331       command('branch', branch)
332     end
333     
334     def branch_delete(branch)
335       command('branch', ['-d', branch])
336     end
337     
338     def checkout(branch, opts = {})
339       arr_opts = []
340       arr_opts << '-f' if opts[:force]
341       arr_opts << branch.to_s
342       
343       command('checkout', arr_opts)
344     end
345     
346     def merge(branch, message = nil)      
347       arr_opts = []
348       arr_opts << ["-m '#{message}'"] if message
349       arr_opts << branch.to_a.join(' ')
350       command('merge', arr_opts)
351     end
352     
353     def remote_add(name, url, opts = {})
354       arr_opts = ['add']
355       arr_opts << '-f' if opts[:with_fetch]
356       arr_opts << name
357       arr_opts << url
358       
359       command('remote', arr_opts)
360     end
361     
362     # this is documented as such, but seems broken for some reason
363     # i'll try to get around it some other way later
364     def remote_remove(name)
365       command('remote', ['rm', name])
366     end
367     
368     def remotes
369       command_lines('remote')
370     end
372     def tags
373       command_lines('tag')
374     end
376     def tag(tag)
377       command('tag', tag)
378     end
380     
381     def fetch(remote)
382       command('fetch', remote.to_s)
383     end
384     
385     def push(remote, branch = 'master')
386       command('push', [remote.to_s, branch.to_s])
387     end
388     
389     def tag_sha(tag_name)
390       command('show-ref',  ['--tags', '-s', tag_name])
391     end  
392     
393     def repack
394       command('repack', ['-a', '-d'])
395     end
396     
397     # reads a tree into the current index file
398     def read_tree(treeish, opts = {})
399       arr_opts = []
400       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
401       arr_opts << treeish.to_a.join(' ')
402       command('read-tree', arr_opts)
403     end
404     
405     def write_tree
406       command('write-tree')
407     end
408     
409     def commit_tree(tree, opts = {})
410       opts[:message] = "commit tree #{tree}" if !opts[:message]
411       t = Tempfile.new('commit-message') do |t|
412         t.write(opts[:message])
413       end
414       
415       arr_opts = []
416       arr_opts << tree
417       arr_opts << "-p #{opts[:parent]}" if opts[:parent]
418       opts[:parents].each { |p| arr_opts << "-p #{p.to_s}" } if opts[:parents]
419       arr_opts << "< #{t.path}"
420       command('commit-tree', arr_opts)
421     end
422     
423     def update_ref(branch, commit)
424       command('update-ref', [branch.to_s, commit.to_s])
425     end
426     
427     def checkout_index(opts = {})
428       arr_opts = []
429       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
430       arr_opts << "--force" if opts[:force]
431       arr_opts << "--all" if opts[:all]
432       arr_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
433       command('checkout-index', arr_opts)
434     end
435     
436     # creates an archive file
437     #
438     # options
439     #  :format  (zip, tar)
440     #  :prefix
441     #  :remote
442     #  :path
443     def archive(sha, file = nil, opts = {})
444       opts[:format] = 'zip' if !opts[:format]
445       
446       if opts[:format] == 'tgz'
447         opts[:format] = 'tar' 
448         opts[:add_gzip] = true
449       end
450       
451       if !file
452         file = Tempfile.new('archive').path
453       end
454       
455       arr_opts = []
456       arr_opts << "--format=#{opts[:format]}" if opts[:format]
457       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
458       arr_opts << "--remote=#{opts[:remote]}" if opts[:remote]
459       arr_opts << sha
460       arr_opts << opts[:path] if opts[:path]
461       arr_opts << '| gzip' if opts[:add_gzip]
462       arr_opts << "> #{file.to_s}"
463       command('archive', arr_opts)
464       return file
465     end
466     
467     private
468     
469     def command_lines(cmd, opts = {}, chdir = true)
470       command(cmd, opts, chdir).split("\n")
471     end
472     
473     def command(cmd, opts = {}, chdir = true)
474       ENV['GIT_DIR'] = @git_dir if (@git_dir != ENV['GIT_DIR'])
475       ENV['GIT_INDEX_FILE'] = @git_index_file if (@git_index_file != ENV['GIT_INDEX_FILE'])
476       ENV['GIT_WORK_TREE'] = @git_work_dir if (@git_work_dir != ENV['GIT_WORK_TREE'])
477       path = @git_work_dir || @git_dir || @path
479       opts = opts.to_a.join(' ')
480       git_cmd = "git #{cmd} #{opts}"
482       out = nil
483       if chdir && (Dir.getwd != path)
484         Dir.chdir(path) { out = `git #{cmd} #{opts} 2>&1`.chomp } 
485       else
486         out = `git #{cmd} #{opts} 2>&1`.chomp
487       end
488       
489       if @logger
490         @logger.info(git_cmd)
491         @logger.debug(out)
492       end
493             
494       if $?.exitstatus > 0
495         if $?.exitstatus == 1 && out == ''
496           return ''
497         end
498         raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s) 
499       end
500       out
501     end
502     
503   end