added a bunch of good stuff to the commit object
[rubygit.git] / lib / git / lib.rb
blob13a3b4cf21775aea2d5eb13c5f37e6c223fc6b14
1 module Git
2   
3   class GitExecuteError < StandardError 
4   end
5   
6   class Lib
7       
8     @git_dir = nil
9     @git_index_file = nil
10     @git_work_dir = nil
11     @path = nil
12         
13     def initialize(base = nil)
14       if base.is_a?(Git::Base)
15         @git_dir = base.repo.path
16         @git_index_file = base.index.path   
17         @git_work_dir = base.dir.path
18       elsif base.is_a?(Hash)
19         @git_dir = base[:repository]
20         @git_index_file = base[:index] 
21         @git_work_dir = base[:working_directory]
22       end
23     end
24     
25     def init
26       command('init')
27     end
28     
29     # tries to clone the given repo
30     #
31     # returns {:repository} (if bare)
32     #         {:working_directory} otherwise
33     #
34     # accepts options:
35     #  :remote - name of remote (rather than 'origin')
36     #  :bare   - no working directory
37     # 
38     # TODO - make this work with SSH password or auth_key
39     #
40     def clone(repository, name, opts = {})
41       @path = opts[:path] || '.'
42       opts[:path] ? clone_dir = File.join(@path, name) : clone_dir = name
43       
44       arr_opts = []
45       arr_opts << "--bare" if opts[:bare]
46       arr_opts << "-o #{opts[:remote]}" if opts[:remote]
47       arr_opts << repository
48       arr_opts << clone_dir
49       
50       command('clone', arr_opts)
51       
52       opts[:bare] ? {:repository => clone_dir} : {:working_directory => clone_dir}
53     end
54     
55     
56     ## READ COMMANDS ##
57     
58     
59     def log_commits(opts = {})
60       arr_opts = ['--pretty=oneline']
61       arr_opts << "-#{opts[:count]}" if opts[:count]
62       arr_opts << "--since=\"#{opts[:since]}\"" if opts[:since].is_a? String
63       arr_opts << "#{opts[:between][0]}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2)
64       arr_opts << opts[:object] if opts[:object].is_a? String
65       arr_opts << '-- ' + opts[:path_limiter] if opts[:path_limiter].is_a? String
66       
67       command_lines('log', arr_opts).map { |l| l.split.first }
68     end
69     
70     def revparse(string)
71       command('rev-parse', string)
72     end
73     
74     def object_type(sha)
75       command('cat-file', ['-t', sha])
76     end
77     
78     def object_size(sha)
79       command('cat-file', ['-s', sha]).to_i
80     end
81     
82     # returns useful array of raw commit object data
83     def commit_data(sha)
84       in_message = false
85       
86       hsh = {'message' => '', 'parent' => []}
87       command_lines('cat-file', ['commit', sha.to_s]).each do |line|
88         if in_message
89           hsh['message'] += line + "\n"
90         end
91         
92         if (line != '') && !in_message
93           data = line.split
94           key = data.shift
95           value = data.join(' ')
96           if key == 'parent'
97             hsh[key] << value
98           else
99             hsh[key] = value
100           end
101         else
102           in_message = true
103         end
104       end
105       hsh
106     end
107     
108     def object_contents(sha)
109       command('cat-file', ['-p', sha])
110     end
112     def branches_all
113       arr = []
114       command_lines('branch', '-a').each do |b| 
115         current = false
116         current = true if b[0, 2] == '* '
117         arr << [b.gsub('* ', '').strip, current]
118       end
119       arr
120     end
122     def branch_current
123       branches_all.select { |b| b[1] }.first[0] rescue nil
124     end
127     # returns hash
128     # [tree-ish] = [[line_no, match], [line_no, match2]]
129     # [tree-ish] = [[line_no, match], [line_no, match2]]
130     def grep(string, opts = {})
131       opts[:object] = 'HEAD' if !opts[:object]
133       grep_opts = ['-n']
134       grep_opts << '-i' if opts[:ignore_case]
135       grep_opts << '-v' if opts[:invert_match]
136       grep_opts << "-e '#{string}'"
137       grep_opts << opts[:object] if opts[:object].is_a?(String)
138       grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
139       hsh = {}
140       command_lines('grep', grep_opts).each do |line|
141         if m = /(.*)\:(\d+)\:(.*)/.match(line)        
142           hsh[m[1]] ||= []
143           hsh[m[1]] << [m[2].to_i, m[3]] 
144         end
145       end
146       hsh
147     end
148     
149     def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
150       diff_opts = ['-p']
151       diff_opts << obj1
152       diff_opts << obj2 if obj2.is_a?(String)
153       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
154       
155       command('diff', diff_opts)
156     end
157     
158     def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
159       diff_opts = ['--numstat']
160       diff_opts << obj1
161       diff_opts << obj2 if obj2.is_a?(String)
162       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
163       
164       hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
165       
166       command_lines('diff', diff_opts).each do |file|
167         (insertions, deletions, filename) = file.split("\t")
168         hsh[:total][:insertions] += insertions.to_i
169         hsh[:total][:deletions] += deletions.to_i
170         hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
171         hsh[:total][:files] += 1
172         hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
173       end
174             
175       hsh
176     end
178     # compares the index and the working directory
179     def diff_files
180       hsh = {}
181       command_lines('diff-files').each do |line|
182         (info, file) = line.split("\t")
183         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
184         hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest, 
185                       :sha_file => sha_src, :sha_index => sha_dest, :type => type}
186       end
187       hsh
188     end
189     
190     # compares the index and the repository
191     def diff_index(treeish)
192       hsh = {}
193       command_lines('diff-index', treeish).each do |line|
194         (info, file) = line.split("\t")
195         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
196         hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest, 
197                       :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
198       end
199       hsh
200     end
201             
202     def ls_files
203       hsh = {}
204       command_lines('ls-files', '--stage').each do |line|
205         (info, file) = line.split("\t")
206         (mode, sha, stage) = info.split
207         hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
208       end
209       hsh
210     end
213     def config_remote(name)
214       hsh = {}
215       command_lines('config', ['--get-regexp', "remote.#{name}"]).each do |line|
216         (key, value) = line.split
217         hsh[key.gsub("remote.#{name}.", '')] = value
218       end
219       hsh
220     end
222     def config_get(name)
223       command('config', ['--get', name])
224     end
225     
226     def config_list
227       hsh = {}
228       command_lines('config', ['--list']).each do |line|
229         (key, value) = line.split('=')
230         hsh[key] = value
231       end
232       hsh
233     end
234     
235     ## WRITE COMMANDS ##
236         
237     def config_set(name, value)
238       command('config', [name, "'#{value}'"])
239     end
240           
241     def add(path = '.')
242       path = path.join(' ') if path.is_a?(Array)
243       command('add', path)
244     end
245     
246     def remove(path = '.', opts = {})
247       path = path.join(' ') if path.is_a?(Array)
249       arr_opts = ['-f']  # overrides the up-to-date check by default
250       arr_opts << ['-r'] if opts[:recursive]
251       arr_opts << path
253       command('rm', arr_opts)
254     end
256     def commit(message, opts = {})
257       arr_opts = ["-m '#{message}'"]
258       arr_opts << '-a' if opts[:add_all]
259       command('commit', arr_opts)
260     end
262     def reset(commit, opts = {})
263       arr_opts = []
264       arr_opts << '--hard' if opts[:hard]
265       arr_opts << commit.to_s if commit
266       command('reset', arr_opts)
267     end
270     def branch_new(branch)
271       command('branch', branch)
272     end
273     
274     def branch_delete(branch)
275       command('branch', ['-d', branch])
276     end
277     
278     def checkout(branch, opts = {})
279       arr_opts = []
280       arr_opts << '-f' if opts[:force]
281       arr_opts << branch.to_s
282       
283       command('checkout', arr_opts)
284     end
285     
286     def merge(branch, message = nil)      
287       arr_opts = []
288       arr_opts << ["-m '#{message}'"] if message
289       arr_opts << branch.to_a.join(' ')
290       command('merge', arr_opts)
291     end
292     
293     def remote_add(name, url, opts = {})
294       arr_opts = ['add']
295       arr_opts << '-f' if opts[:with_fetch]
296       arr_opts << name
297       arr_opts << url
298       
299       command('remote', arr_opts)
300     end
301     
302     # this is documented as such, but seems broken for some reason
303     # i'll try to get around it some other way later
304     def remote_remove(name)
305       command('remote', ['rm', name])
306     end
307     
308     def remotes
309       command_lines('remote')
310     end
312     def tags
313       command_lines('tag')
314     end
316     def tag(tag)
317       command('tag', tag)
318     end
320     
321     def fetch(remote)
322       command('fetch', remote.to_s)
323     end
324     
325     def push(remote, branch = 'master')
326       command('push', [remote.to_s, branch.to_s])
327     end
328     
329     def tag_sha(tag_name)
330       command('show-ref',  ['--tags', '-s', tag_name])
331     end  
332     
333     def repack
334       command('repack', ['-a', '-d'])
335     end
336     
337     private
338     
339     def command_lines(cmd, opts = {})
340       command(cmd, opts).split("\n")
341     end
342     
343     def command(cmd, opts = {})
344       ENV['GIT_DIR'] = @git_dir 
345       ENV['GIT_INDEX_FILE'] = @git_index_file 
346       ENV['GIT_WORK_DIR'] = @git_work_dir 
347       path = @git_work_dir || @git_dir || @path
348       Dir.chdir(path) do  
349         opts = opts.to_a.join(' ')
350         git_cmd = "git #{cmd} #{opts}"
351         out = `git #{cmd} #{opts} 2>&1`.chomp
352         #puts path
353         #puts "gd: #{@git_work_dir}"
354         #puts "gi: #{@git_index_file}"
355         #puts "pp: #{@path}"
356         #puts git_cmd
357         #puts out
358         #puts
359         if $?.exitstatus > 0
360           if $?.exitstatus == 1 && out == ''
361             return ''
362           end
363           raise Git::GitExecuteError.new(git_cmd + ':' + out.to_s)
364         end
365         out
366       end
367     end
368     
369   end