added tagging
[rubygit.git] / lib / git / lib.rb
blob93490dbe4835636b81f9946389a45b457b263569
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     def object_contents(sha)
83       command('cat-file', ['-p', sha])
84     end
86     def branches_all
87       arr = []
88       command_lines('branch', '-a').each do |b| 
89         current = false
90         current = true if b[0, 2] == '* '
91         arr << [b.gsub('* ', '').strip, current]
92       end
93       arr
94     end
96     def branch_current
97       branches_all.select { |b| b[1] }.first[0] rescue nil
98     end
101     # returns hash
102     # [tree-ish] = [[line_no, match], [line_no, match2]]
103     # [tree-ish] = [[line_no, match], [line_no, match2]]
104     def grep(string, opts = {})
105       opts[:object] = 'HEAD' if !opts[:object]
107       grep_opts = ['-n']
108       grep_opts << '-i' if opts[:ignore_case]
109       grep_opts << '-v' if opts[:invert_match]
110       grep_opts << "-e '#{string}'"
111       grep_opts << opts[:object] if opts[:object].is_a?(String)
112       grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
113       hsh = {}
114       command_lines('grep', grep_opts).each do |line|
115         if m = /(.*)\:(\d+)\:(.*)/.match(line)        
116           hsh[m[1]] ||= []
117           hsh[m[1]] << [m[2].to_i, m[3]] 
118         end
119       end
120       hsh
121     end
122     
123     def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
124       diff_opts = ['-p']
125       diff_opts << obj1
126       diff_opts << obj2 if obj2.is_a?(String)
127       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
128       
129       command('diff', diff_opts)
130     end
131     
132     def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
133       diff_opts = ['--numstat']
134       diff_opts << obj1
135       diff_opts << obj2 if obj2.is_a?(String)
136       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
137       
138       hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
139       
140       command_lines('diff', diff_opts).each do |file|
141         (insertions, deletions, filename) = file.split("\t")
142         hsh[:total][:insertions] += insertions.to_i
143         hsh[:total][:deletions] += deletions.to_i
144         hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
145         hsh[:total][:files] += 1
146         hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
147       end
148             
149       hsh
150     end
152     # compares the index and the working directory
153     def diff_files
154       hsh = {}
155       command_lines('diff-files').each do |line|
156         (info, file) = line.split("\t")
157         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
158         hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest, 
159                       :sha_file => sha_src, :sha_index => sha_dest, :type => type}
160       end
161       hsh
162     end
163     
164     # compares the index and the repository
165     def diff_index(treeish)
166       hsh = {}
167       command_lines('diff-index', treeish).each do |line|
168         (info, file) = line.split("\t")
169         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
170         hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest, 
171                       :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
172       end
173       hsh
174     end
175             
176     def ls_files
177       hsh = {}
178       command_lines('ls-files', '--stage').each do |line|
179         (info, file) = line.split("\t")
180         (mode, sha, stage) = info.split
181         hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
182       end
183       hsh
184     end
187     def config_remote(name)
188       hsh = {}
189       command_lines('config', ['--get-regexp', "remote.#{name}"]).each do |line|
190         (key, value) = line.split
191         hsh[key.gsub("remote.#{name}.", '')] = value
192       end
193       hsh
194     end
196     def config_get(name)
197       command('config', ['--get', name])
198     end
199     
200     def config_list
201       hsh = {}
202       command_lines('config', ['--list']).each do |line|
203         (key, value) = line.split('=')
204         hsh[key] = value
205       end
206       hsh
207     end
208     
209     ## WRITE COMMANDS ##
210         
211     def config_set(name, value)
212       command('config', [name, "'#{value}'"])
213     end
214           
215     def add(path = '.')
216       path = path.join(' ') if path.is_a?(Array)
217       command('add', path)
218     end
219     
220     def remove(path = '.', opts = {})
221       path = path.join(' ') if path.is_a?(Array)
223       arr_opts = ['-f']  # overrides the up-to-date check by default
224       arr_opts << ['-r'] if opts[:recursive]
225       arr_opts << path
227       command('rm', arr_opts)
228     end
230     def commit(message, opts = {})
231       arr_opts = ["-m '#{message}'"]
232       arr_opts << '-a' if opts[:add_all]
233       command('commit', arr_opts)
234     end
236     def reset(commit, opts = {})
237       arr_opts = []
238       arr_opts << '--hard' if opts[:hard]
239       arr_opts << commit.to_s if commit
240       command('reset', arr_opts)
241     end
244     def branch_new(branch)
245       command('branch', branch)
246     end
247     
248     def branch_delete(branch)
249       command('branch', ['-d', branch])
250     end
251     
252     def checkout(branch, opts = {})
253       arr_opts = []
254       arr_opts << '-f' if opts[:force]
255       arr_opts << branch.to_s
256       
257       command('checkout', arr_opts)
258     end
259     
260     def merge(branch, message = nil)
261       arr_opts = []
262       arr_opts << ["-m '#{message}'"] if message
263       arr_opts << branch.to_a.join(' ')
264       command('merge', arr_opts)
265     end
266     
267     def remote_add(name, url, opts = {})
268       arr_opts = ['add']
269       arr_opts << '-f' if opts[:with_fetch]
270       arr_opts << name
271       arr_opts << url
272       
273       command('remote', arr_opts)
274     end
275     
276     # this is documented as such, but seems broken for some reason
277     # i'll try to get around it some other way later
278     def remote_remove(name)
279       command('remote', ['rm', name])
280     end
281     
282     def remotes
283       command_lines('remote')
284     end
286     def tags
287       command_lines('tag')
288     end
290     def tag(tag)
291       command('tag', tag)
292     end
294     
295     def fetch(remote)
296       command('fetch', remote.to_s)
297     end
298     
299     def tag_sha(tag_name)
300       command('show-ref',  ['--tags', '-s', tag_name])
301     end  
302     
303     
304     
305     private
306     
307     def command_lines(cmd, opts = {})
308       command(cmd, opts).split("\n")
309     end
310     
311     def command(cmd, opts = {})
312       ENV['GIT_DIR'] = @git_dir 
313       ENV['GIT_INDEX_FILE'] = @git_index_file 
314       ENV['GIT_WORK_DIR'] = @git_work_dir 
315       path = @git_work_dir || @git_dir || @path
316       Dir.chdir(path) do  
317         opts = opts.to_a.join(' ')
318         git_cmd = "git #{cmd} #{opts}"
319         out = `git #{cmd} #{opts} 2>&1`.chomp
320         #puts path
321         #puts "gd: #{@git_work_dir}"
322         #puts "gi: #{@git_index_file}"
323         #puts "pp: #{@path}"
324         #puts git_cmd
325         #puts out
326         #puts
327         if $?.exitstatus > 0
328           if $?.exitstatus == 1 && out == ''
329             return ''
330           end
331           raise Git::GitExecuteError.new(git_cmd + out.to_s)
332         end
333         out
334       end
335     end
336     
337   end