OSDN Git Service

scm: git: add methods of getting git version and add unit lib test (#4273).
[redminele/redmine.git] / lib / redmine / scm / adapters / git_adapter.rb
1 # redMine - project management software
2 # Copyright (C) 2006-2007  Jean-Philippe Lang
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17
18 require 'redmine/scm/adapters/abstract_adapter'
19
20 module Redmine
21   module Scm
22     module Adapters
23       class GitAdapter < AbstractAdapter
24         # Git executable name
25         GIT_BIN = Redmine::Configuration['scm_git_command'] || "git"
26
27         class << self
28           def client_command
29             @@bin    ||= GIT_BIN
30           end
31
32           def sq_bin
33             @@sq_bin ||= shell_quote(GIT_BIN)
34           end
35
36           def client_version
37             @@client_version ||= (scm_command_version || [])
38           end
39
40           def client_available
41             !client_version.empty?
42           end
43
44           def scm_command_version
45             scm_version = scm_version_from_command_line
46             if m = scm_version.match(%r{\A(.*?)((\d+\.)+\d+)})
47               m[2].scan(%r{\d+}).collect(&:to_i)
48             end
49           end
50
51           def scm_version_from_command_line
52             shellout("#{sq_bin} --version") { |io| io.read }.to_s
53           end
54         end
55
56         def info
57           begin
58             Info.new(:root_url => url, :lastrev => lastrev('',nil))
59           rescue
60             nil
61           end
62         end
63
64         def branches
65           return @branches if @branches
66           @branches = []
67           cmd = "#{self.class.sq_bin} --git-dir #{target('')} branch --no-color"
68           shellout(cmd) do |io|
69             io.each_line do |line|
70               @branches << line.match('\s*\*?\s*(.*)$')[1]
71             end
72           end
73           @branches.sort!
74         end
75
76         def tags
77           return @tags if @tags
78           cmd = "#{self.class.sq_bin} --git-dir #{target('')} tag"
79           shellout(cmd) do |io|
80             @tags = io.readlines.sort!.map{|t| t.strip}
81           end
82         end
83
84         def default_branch
85           branches.include?('master') ? 'master' : branches.first 
86         end
87         
88         def entries(path=nil, identifier=nil)
89           path ||= ''
90           entries = Entries.new
91           cmd = "#{self.class.sq_bin} --git-dir #{target('')} ls-tree -l "
92           cmd << shell_quote("HEAD:" + path) if identifier.nil?
93           cmd << shell_quote(identifier + ":" + path) if identifier
94           shellout(cmd)  do |io|
95             io.each_line do |line|
96               e = line.chomp.to_s
97               if e =~ /^\d+\s+(\w+)\s+([0-9a-f]{40})\s+([0-9-]+)\t(.+)$/
98                 type = $1
99                 sha = $2
100                 size = $3
101                 name = $4
102                 full_path = path.empty? ? name : "#{path}/#{name}"
103                 entries << Entry.new({:name => name,
104                  :path => full_path,
105                  :kind => (type == "tree") ? 'dir' : 'file',
106                  :size => (type == "tree") ? nil : size,
107                  :lastrev => lastrev(full_path,identifier)
108                 }) unless entries.detect{|entry| entry.name == name}
109               end
110             end
111           end
112           return nil if $? && $?.exitstatus != 0
113           entries.sort_by_name
114         end
115
116         def lastrev(path,rev)
117           return nil if path.nil?
118           cmd = "#{self.class.sq_bin} --git-dir #{target('')} log --no-color --date=iso --pretty=fuller --no-merges -n 1 "
119           cmd << " #{shell_quote rev} " if rev 
120           cmd <<  "-- #{shell_quote path} " unless path.empty?
121           lines = []
122           shellout(cmd) { |io| lines = io.readlines }
123           return nil if $? && $?.exitstatus != 0
124           begin
125               id = lines[0].split[1]
126               author = lines[1].match('Author:\s+(.*)$')[1]
127               time = Time.parse(lines[4].match('CommitDate:\s+(.*)$')[1])
128
129               Revision.new({
130                 :identifier => id,
131                 :scmid => id,
132                 :author => author, 
133                 :time => time,
134                 :message => nil, 
135                 :paths => nil 
136               })
137           rescue NoMethodError => e
138               logger.error("The revision '#{path}' has a wrong format")
139               return nil
140           end
141         end
142
143         def revisions(path, identifier_from, identifier_to, options={})
144           revisions = Revisions.new
145
146           cmd = "#{self.class.sq_bin} --git-dir #{target('')} log --no-color --raw --date=iso --pretty=fuller "
147           cmd << " --reverse " if options[:reverse]
148           cmd << " --all " if options[:all]
149           cmd << " -n #{options[:limit].to_i} " if options[:limit]
150           cmd << "#{shell_quote(identifier_from + '..')}" if identifier_from
151           cmd << "#{shell_quote identifier_to}" if identifier_to
152           cmd << " --since=#{shell_quote(options[:since].strftime("%Y-%m-%d %H:%M:%S"))}" if options[:since]
153           cmd << " -- #{shell_quote path}" if path && !path.empty?
154
155           shellout(cmd) do |io|
156             files=[]
157             changeset = {}
158             parsing_descr = 0  #0: not parsing desc or files, 1: parsing desc, 2: parsing files
159             revno = 1
160
161             io.each_line do |line|
162               if line =~ /^commit ([0-9a-f]{40})$/
163                 key = "commit"
164                 value = $1
165                 if (parsing_descr == 1 || parsing_descr == 2)
166                   parsing_descr = 0
167                   revision = Revision.new({
168                     :identifier => changeset[:commit],
169                     :scmid => changeset[:commit],
170                     :author => changeset[:author],
171                     :time => Time.parse(changeset[:date]),
172                     :message => changeset[:description],
173                     :paths => files
174                   })
175                   if block_given?
176                     yield revision
177                   else
178                     revisions << revision
179                   end
180                   changeset = {}
181                   files = []
182                   revno = revno + 1
183                 end
184                 changeset[:commit] = $1
185               elsif (parsing_descr == 0) && line =~ /^(\w+):\s*(.*)$/
186                 key = $1
187                 value = $2
188                 if key == "Author"
189                   changeset[:author] = value
190                 elsif key == "CommitDate"
191                   changeset[:date] = value
192                 end
193               elsif (parsing_descr == 0) && line.chomp.to_s == ""
194                 parsing_descr = 1
195                 changeset[:description] = ""
196               elsif (parsing_descr == 1 || parsing_descr == 2) \
197               && line =~ /^:\d+\s+\d+\s+[0-9a-f.]+\s+[0-9a-f.]+\s+(\w)\t(.+)$/
198                 parsing_descr = 2
199                 fileaction = $1
200                 filepath = $2
201                 files << {:action => fileaction, :path => filepath}
202               elsif (parsing_descr == 1 || parsing_descr == 2) \
203               && line =~ /^:\d+\s+\d+\s+[0-9a-f.]+\s+[0-9a-f.]+\s+(\w)\d+\s+(\S+)\t(.+)$/
204                 parsing_descr = 2
205                 fileaction = $1
206                 filepath = $3
207                 files << {:action => fileaction, :path => filepath}
208               elsif (parsing_descr == 1) && line.chomp.to_s == ""
209                 parsing_descr = 2
210               elsif (parsing_descr == 1)
211                 changeset[:description] << line[4..-1]
212               end
213             end 
214
215             if changeset[:commit]
216               revision = Revision.new({
217                 :identifier => changeset[:commit],
218                 :scmid => changeset[:commit],
219                 :author => changeset[:author],
220                 :time => Time.parse(changeset[:date]),
221                 :message => changeset[:description],
222                 :paths => files
223               })
224
225               if block_given?
226                 yield revision
227               else
228                 revisions << revision
229               end
230             end
231           end
232
233           return nil if $? && $?.exitstatus != 0
234           revisions
235         end
236
237         def diff(path, identifier_from, identifier_to=nil)
238           path ||= ''
239
240           if identifier_to
241             cmd = "#{self.class.sq_bin} --git-dir #{target('')} diff --no-color #{shell_quote identifier_to} #{shell_quote identifier_from}" 
242           else
243             cmd = "#{self.class.sq_bin} --git-dir #{target('')} show --no-color #{shell_quote identifier_from}"
244           end
245
246           cmd << " -- #{shell_quote path}" unless path.empty?
247           diff = []
248           shellout(cmd) do |io|
249             io.each_line do |line|
250               diff << line
251             end
252           end
253           return nil if $? && $?.exitstatus != 0
254           diff
255         end
256         
257         def annotate(path, identifier=nil)
258           identifier = 'HEAD' if identifier.blank?
259           cmd = "#{self.class.sq_bin} --git-dir #{target('')} blame -p #{shell_quote identifier} -- #{shell_quote path}"
260           blame = Annotate.new
261           content = nil
262           shellout(cmd) { |io| io.binmode; content = io.read }
263           return nil if $? && $?.exitstatus != 0
264           # git annotates binary files
265           return nil if content.is_binary_data?
266           identifier = ''
267           # git shows commit author on the first occurrence only
268           authors_by_commit = {}
269           content.split("\n").each do |line|
270             if line =~ /^([0-9a-f]{39,40})\s.*/
271               identifier = $1
272             elsif line =~ /^author (.+)/
273               authors_by_commit[identifier] = $1.strip
274             elsif line =~ /^\t(.*)/
275               blame.add_line($1, Revision.new(:identifier => identifier, :author => authors_by_commit[identifier]))
276               identifier = ''
277               author = ''
278             end
279           end
280           blame
281         end
282         
283         def cat(path, identifier=nil)
284           if identifier.nil?
285             identifier = 'HEAD'
286           end
287           cmd = "#{self.class.sq_bin} --git-dir #{target('')} show --no-color #{shell_quote(identifier + ':' + path)}"
288           cat = nil
289           shellout(cmd) do |io|
290             io.binmode
291             cat = io.read
292           end
293           return nil if $? && $?.exitstatus != 0
294           cat
295         end
296
297         class Revision < Redmine::Scm::Adapters::Revision
298           # Returns the readable identifier
299           def format_identifier
300             identifier[0,8]
301           end
302         end
303       end
304     end
305   end
306 end