updated the docs
[rubygit.git] / lib / git / lib.rb
blob76223dea615630cf77d49865ab4472114ee2cfe1
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     def initialize(base = nil)
16       if base.is_a?(Git::Base)
17         @git_dir = base.repo.path
18         @git_index_file = base.index.path if base.index
19         @git_work_dir = base.dir.path if base.dir
20       elsif base.is_a?(Hash)
21         @git_dir = base[:repository]
22         @git_index_file = base[:index] 
23         @git_work_dir = base[:working_directory]
24       end
25     end
26     
27     def init
28       command('init')
29     end
30     
31     # tries to clone the given repo
32     #
33     # returns {:repository} (if bare)
34     #         {:working_directory} otherwise
35     #
36     # accepts options:
37     #  :remote - name of remote (rather than 'origin')
38     #  :bare   - no working directory
39     # 
40     # TODO - make this work with SSH password or auth_key
41     #
42     def clone(repository, name, opts = {})
43       @path = opts[:path] || '.'
44       opts[:path] ? clone_dir = File.join(@path, name) : clone_dir = name
45       
46       arr_opts = []
47       arr_opts << "--bare" if opts[:bare]
48       arr_opts << "-o #{opts[:remote]}" if opts[:remote]
49       arr_opts << repository
50       arr_opts << clone_dir
51       
52       command('clone', arr_opts)
53       
54       opts[:bare] ? {:repository => clone_dir} : {:working_directory => clone_dir}
55     end
56     
57     
58     ## READ COMMANDS ##
59     
60     
61     def log_commits(opts = {})
62       arr_opts = ['--pretty=oneline']
63       arr_opts << "-#{opts[:count]}" if opts[:count]
64       arr_opts << "--since=\"#{opts[:since]}\"" if opts[:since].is_a? String
65       arr_opts << "#{opts[:between][0]}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2)
66       arr_opts << opts[:object] if opts[:object].is_a? String
67       arr_opts << '-- ' + opts[:path_limiter] if opts[:path_limiter].is_a? String
68       
69       command_lines('log', arr_opts).map { |l| l.split.first }
70     end
71     
72     def revparse(string)
73       command('rev-parse', string)
74     end
75     
76     def namerev(string)
77       command('name-rev', string).split[1]
78     end
79     
80     def object_type(sha)
81       command('cat-file', ['-t', sha])
82     end
83     
84     def object_size(sha)
85       command('cat-file', ['-s', sha]).to_i
86     end
87     
88     # returns useful array of raw commit object data
89     def commit_data(sha)
90       in_message = false
91       
92       hsh = {'message' => '', 'parent' => []}
93       command_lines('cat-file', ['commit', sha.to_s]).each do |line|
94         if in_message
95           hsh['message'] += line + "\n"
96         end
97         
98         if (line != '') && !in_message
99           data = line.split
100           key = data.shift
101           value = data.join(' ')
102           if key == 'parent'
103             hsh[key] << value
104           else
105             hsh[key] = value
106           end
107         else
108           in_message = true
109         end
110       end
111       hsh
112     end
113     
114     def object_contents(sha)
115       command('cat-file', ['-p', sha])
116     end
118     def ls_tree(sha)
119       data = {'blob' => {}, 'tree' => {}}
120       command_lines('ls-tree', sha.to_s).each do |line|
121         (info, filenm) = line.split("\t")
122         (mode, type, sha) = info.split
123         data[type][filenm] = {:mode => mode, :sha => sha}
124       end
125       data
126     end
128     def branches_all
129       arr = []
130       command_lines('branch', '-a').each do |b| 
131         current = false
132         current = true if b[0, 2] == '* '
133         arr << [b.gsub('* ', '').strip, current]
134       end
135       arr
136     end
138     def branch_current
139       branches_all.select { |b| b[1] }.first[0] rescue nil
140     end
143     # returns hash
144     # [tree-ish] = [[line_no, match], [line_no, match2]]
145     # [tree-ish] = [[line_no, match], [line_no, match2]]
146     def grep(string, opts = {})
147       opts[:object] = 'HEAD' if !opts[:object]
149       grep_opts = ['-n']
150       grep_opts << '-i' if opts[:ignore_case]
151       grep_opts << '-v' if opts[:invert_match]
152       grep_opts << "-e '#{string}'"
153       grep_opts << opts[:object] if opts[:object].is_a?(String)
154       grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
155       hsh = {}
156       command_lines('grep', grep_opts).each do |line|
157         if m = /(.*)\:(\d+)\:(.*)/.match(line)        
158           hsh[m[1]] ||= []
159           hsh[m[1]] << [m[2].to_i, m[3]] 
160         end
161       end
162       hsh
163     end
164     
165     def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
166       diff_opts = ['-p']
167       diff_opts << obj1
168       diff_opts << obj2 if obj2.is_a?(String)
169       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
170       
171       command('diff', diff_opts)
172     end
173     
174     def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
175       diff_opts = ['--numstat']
176       diff_opts << obj1
177       diff_opts << obj2 if obj2.is_a?(String)
178       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
179       
180       hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
181       
182       command_lines('diff', diff_opts).each do |file|
183         (insertions, deletions, filename) = file.split("\t")
184         hsh[:total][:insertions] += insertions.to_i
185         hsh[:total][:deletions] += deletions.to_i
186         hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
187         hsh[:total][:files] += 1
188         hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
189       end
190             
191       hsh
192     end
194     # compares the index and the working directory
195     def diff_files
196       hsh = {}
197       command_lines('diff-files').each do |line|
198         (info, file) = line.split("\t")
199         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
200         hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest, 
201                       :sha_file => sha_src, :sha_index => sha_dest, :type => type}
202       end
203       hsh
204     end
205     
206     # compares the index and the repository
207     def diff_index(treeish)
208       hsh = {}
209       command_lines('diff-index', treeish).each do |line|
210         (info, file) = line.split("\t")
211         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
212         hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest, 
213                       :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
214       end
215       hsh
216     end
217             
218     def ls_files
219       hsh = {}
220       command_lines('ls-files', '--stage').each do |line|
221         (info, file) = line.split("\t")
222         (mode, sha, stage) = info.split
223         hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
224       end
225       hsh
226     end
229     def config_remote(name)
230       hsh = {}
231       command_lines('config', ['--get-regexp', "remote.#{name}"]).each do |line|
232         (key, value) = line.split
233         hsh[key.gsub("remote.#{name}.", '')] = value
234       end
235       hsh
236     end
238     def config_get(name)
239       command('config', ['--get', name])
240     end
241     
242     def config_list
243       hsh = {}
244       command_lines('config', ['--list']).each do |line|
245         (key, value) = line.split('=')
246         hsh[key] = value
247       end
248       hsh
249     end
250     
251     ## WRITE COMMANDS ##
252         
253     def config_set(name, value)
254       command('config', [name, "'#{value}'"])
255     end
256           
257     def add(path = '.')
258       path = path.join(' ') if path.is_a?(Array)
259       command('add', path)
260     end
261     
262     def remove(path = '.', opts = {})
263       path = path.join(' ') if path.is_a?(Array)
265       arr_opts = ['-f']  # overrides the up-to-date check by default
266       arr_opts << ['-r'] if opts[:recursive]
267       arr_opts << path
269       command('rm', arr_opts)
270     end
272     def commit(message, opts = {})
273       arr_opts = ["-m '#{message}'"]
274       arr_opts << '-a' if opts[:add_all]
275       command('commit', arr_opts)
276     end
278     def reset(commit, opts = {})
279       arr_opts = []
280       arr_opts << '--hard' if opts[:hard]
281       arr_opts << commit.to_s if commit
282       command('reset', arr_opts)
283     end
286     def branch_new(branch)
287       command('branch', branch)
288     end
289     
290     def branch_delete(branch)
291       command('branch', ['-d', branch])
292     end
293     
294     def checkout(branch, opts = {})
295       arr_opts = []
296       arr_opts << '-f' if opts[:force]
297       arr_opts << branch.to_s
298       
299       command('checkout', arr_opts)
300     end
301     
302     def merge(branch, message = nil)      
303       arr_opts = []
304       arr_opts << ["-m '#{message}'"] if message
305       arr_opts << branch.to_a.join(' ')
306       command('merge', arr_opts)
307     end
308     
309     def remote_add(name, url, opts = {})
310       arr_opts = ['add']
311       arr_opts << '-f' if opts[:with_fetch]
312       arr_opts << name
313       arr_opts << url
314       
315       command('remote', arr_opts)
316     end
317     
318     # this is documented as such, but seems broken for some reason
319     # i'll try to get around it some other way later
320     def remote_remove(name)
321       command('remote', ['rm', name])
322     end
323     
324     def remotes
325       command_lines('remote')
326     end
328     def tags
329       command_lines('tag')
330     end
332     def tag(tag)
333       command('tag', tag)
334     end
336     
337     def fetch(remote)
338       command('fetch', remote.to_s)
339     end
340     
341     def push(remote, branch = 'master')
342       command('push', [remote.to_s, branch.to_s])
343     end
344     
345     def tag_sha(tag_name)
346       command('show-ref',  ['--tags', '-s', tag_name])
347     end  
348     
349     def repack
350       command('repack', ['-a', '-d'])
351     end
352     
353     # reads a tree into the current index file
354     def read_tree(treeish, opts = {})
355       arr_opts = []
356       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
357       arr_opts << treeish.to_a.join(' ')
358       command('read-tree', arr_opts)
359     end
360     
361     def write_tree
362       command('write-tree')
363     end
364     
365     def commit_tree(tree, opts = {})
366       opts[:message] = "commit tree #{tree}" if !opts[:message]
367       t = Tempfile.new('commit-message') do |t|
368         t.write(opts[:message])
369       end
370       
371       arr_opts = []
372       arr_opts << tree
373       arr_opts << "-p #{opts[:parent]}" if opts[:parent]
374       opts[:parents].each { |p| arr_opts << "-p #{p.to_s}" } if opts[:parents]
375       arr_opts << "< #{t.path}"
376       command('commit-tree', arr_opts)
377     end
378     
379     def update_ref(branch, commit)
380       command('update-ref', [branch.to_s, commit.to_s])
381     end
382     
383     def checkout_index(opts = {})
384       arr_opts = []
385       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
386       arr_opts << "--force" if opts[:force]
387       arr_opts << "--all" if opts[:all]
388       arr_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
389       command('checkout-index', arr_opts)
390     end
391     
392     # creates an archive file
393     #
394     # options
395     #  :format  (zip, tar)
396     #  :prefix
397     #  :remote
398     #  :path
399     def archive(sha, file = nil, opts = {})
400       opts[:format] = 'zip' if !opts[:format]
401       
402       if opts[:format] == 'tgz'
403         opts[:format] = 'tar' 
404         opts[:add_gzip] = true
405       end
406       
407       if !file
408         file = Tempfile.new('archive').path
409       end
410       
411       arr_opts = []
412       arr_opts << "--format=#{opts[:format]}" if opts[:format]
413       arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix]
414       arr_opts << "--remote=#{opts[:remote]}" if opts[:remote]
415       arr_opts << sha
416       arr_opts << opts[:path] if opts[:path]
417       arr_opts << '| gzip' if opts[:add_gzip]
418       arr_opts << "> #{file.to_s}"
419       command('archive', arr_opts)
420       return file
421     end
422     
423     private
424     
425     def command_lines(cmd, opts = {})
426       command(cmd, opts).split("\n")
427     end
428     
429     def command(cmd, opts = {})
430       ENV['GIT_DIR'] = @git_dir if (@git_dir != ENV['GIT_DIR'])
431       ENV['GIT_INDEX_FILE'] = @git_index_file if (@git_index_file != ENV['GIT_INDEX_FILE'])
432       ENV['GIT_WORK_DIR'] = @git_work_dir if (@git_work_dir != ENV['GIT_WORK_DIR'])
433       #path = @git_work_dir || @git_dir || @path
434       #Dir.chdir(path) do  
435         opts = opts.to_a.join(' ')
436         git_cmd = "git #{cmd} #{opts}"
437         out = `git #{cmd} #{opts} 2>&1`.chomp
438         #puts path
439         #puts "gd: #{@git_work_dir}"
440         #puts "gi: #{@git_index_file}"
441         #puts "pp: #{@path}"
442         #puts git_cmd
443         #puts out
444         #puts
445         if $?.exitstatus > 0
446           if $?.exitstatus == 1 && out == ''
447             return ''
448           end
449           raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s) 
450         end
451         out
452       #end
453     end
454     
455   end