added remove and reset
[rubygit.git] / lib / git / lib.rb
blobbc40e0cea6db01865b33baf184241cc055893609
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     # returns hash
97     # [tree-ish] = [[line_no, match], [line_no, match2]]
98     # [tree-ish] = [[line_no, match], [line_no, match2]]
99     def grep(string, opts = {})
100       opts[:object] = 'HEAD' if !opts[:object]
102       grep_opts = ['-n']
103       grep_opts << '-i' if opts[:ignore_case]
104       grep_opts << '-v' if opts[:invert_match]
105       grep_opts << "-e '#{string}'"
106       grep_opts << opts[:object] if opts[:object].is_a?(String)
107       grep_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
108       hsh = {}
109       command_lines('grep', grep_opts).each do |line|
110         if m = /(.*)\:(\d+)\:(.*)/.match(line)        
111           hsh[m[1]] ||= []
112           hsh[m[1]] << [m[2].to_i, m[3]] 
113         end
114       end
115       hsh
116     end
117     
118     def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
119       diff_opts = ['-p']
120       diff_opts << obj1
121       diff_opts << obj2 if obj2.is_a?(String)
122       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
123       
124       command('diff', diff_opts)
125     end
126     
127     def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
128       diff_opts = ['--numstat']
129       diff_opts << obj1
130       diff_opts << obj2 if obj2.is_a?(String)
131       diff_opts << ('-- ' + opts[:path_limiter]) if opts[:path_limiter].is_a? String
132       
133       hsh = {:total => {:insertions => 0, :deletions => 0, :lines => 0, :files => 0}, :files => {}}
134       
135       command_lines('diff', diff_opts).each do |file|
136         (insertions, deletions, filename) = file.split("\t")
137         hsh[:total][:insertions] += insertions.to_i
138         hsh[:total][:deletions] += deletions.to_i
139         hsh[:total][:lines] = (hsh[:total][:deletions] + hsh[:total][:insertions])
140         hsh[:total][:files] += 1
141         hsh[:files][filename] = {:insertions => insertions.to_i, :deletions => deletions.to_i}
142       end
143             
144       hsh
145     end
147     # compares the index and the working directory
148     def diff_files
149       hsh = {}
150       command_lines('diff-files').each do |line|
151         (info, file) = line.split("\t")
152         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
153         hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest, 
154                       :sha_file => sha_src, :sha_index => sha_dest, :type => type}
155       end
156       hsh
157     end
158     
159     # compares the index and the repository
160     def diff_index(treeish)
161       hsh = {}
162       command_lines('diff-index', treeish).each do |line|
163         (info, file) = line.split("\t")
164         (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
165         hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest, 
166                       :sha_repo => sha_src, :sha_index => sha_dest, :type => type}
167       end
168       hsh
169     end
170             
171     def ls_files
172       hsh = {}
173       command_lines('ls-files', '--stage').each do |line|
174         (info, file) = line.split("\t")
175         (mode, sha, stage) = info.split
176         hsh[file] = {:path => file, :mode_index => mode, :sha_index => sha, :stage => stage}
177       end
178       hsh
179     end
182     def config_remote(name)
183       hsh = {}
184       command_lines('config', ['--get-regexp', "remote.#{name}"]).each do |line|
185         (key, value) = line.split
186         hsh[key.gsub("remote.#{name}.", '')] = value
187       end
188       hsh
189     end
191     def config_get(name)
192       command('config', ['--get', name])
193     end
194     
195     def config_list
196       hsh = {}
197       command_lines('config', ['--list']).each do |line|
198         (key, value) = line.split('=')
199         hsh[key] = value
200       end
201       hsh
202     end
203     
204     ## WRITE COMMANDS ##
205         
206     def config_set(name, value)
207       command('config', [name, "'#{value}'"])
208     end
209           
210     def add(path = '.')
211       path = path.join(' ') if path.is_a?(Array)
212       command('add', path)
213     end
214     
215     def remove(path = '.', opts = {})
216       path = path.join(' ') if path.is_a?(Array)
218       arr_opts = ['-f']  # overrides the up-to-date check by default
219       arr_opts << ['-r'] if opts[:recursive]
220       arr_opts << path
222       command('rm', arr_opts)
223     end
225     def commit(message, opts = {})
226       arr_opts = ["-m '#{message}'"]
227       arr_opts << '-a' if opts[:add_all]
228       command('commit', arr_opts)
229     end
231     def reset(commit, opts = {})
232       arr_opts = []
233       arr_opts << '--hard' if opts[:hard]
234       arr_opts << commit.to_s if commit
235       command('reset', arr_opts)
236     end
238     
239     private
240     
241     def command_lines(cmd, opts = {})
242       command(cmd, opts).split("\n")
243     end
244     
245     def command(cmd, opts = {})
246       ENV['GIT_DIR'] = @git_dir 
247       ENV['GIT_INDEX_FILE'] = @git_index_file 
248       ENV['GIT_WORK_DIR'] = @git_work_dir 
249       path = @git_work_dir || @git_dir || @path
250       Dir.chdir(path) do  
251         opts = opts.to_a.join(' ')
252         out = `git #{cmd} #{opts} 2>&1`.chomp
253         #puts path
254         #puts "gd: #{@git_work_dir}"
255         #puts "gi: #{@git_index_file}"
256         #puts "pp: #{@path}"
257         #puts "git #{cmd} #{opts}"
258         #puts out
259         #puts
260         if $?.exitstatus > 1
261           raise Git::GitExecuteError.new(out)
262         end
263         out
264       end
265     end
266     
267   end