OSDN Git Service

scm: git: convert path encoding in "git log" (#5251).
[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
25         SCM_GIT_REPORT_LAST_COMMIT = true
26
27         # Git executable name
28         GIT_BIN = Redmine::Configuration['scm_git_command'] || "git"
29
30         # raised if scm command exited with error, e.g. unknown revision.
31         class ScmCommandAborted < CommandFailed; end
32
33         class << self
34           def client_command
35             @@bin    ||= GIT_BIN
36           end
37
38           def sq_bin
39             @@sq_bin ||= shell_quote(GIT_BIN)
40           end
41
42           def client_version
43             @@client_version ||= (scm_command_version || [])
44           end
45
46           def client_available
47             !client_version.empty?
48           end
49
50           def scm_command_version
51             scm_version = scm_version_from_command_line.dup
52             if scm_version.respond_to?(:force_encoding)
53               scm_version.force_encoding('ASCII-8BIT')
54             end
55             if m = scm_version.match(%r{\A(.*?)((\d+\.)+\d+)})
56               m[2].scan(%r{\d+}).collect(&:to_i)
57             end
58           end
59
60           def scm_version_from_command_line
61             shellout("#{sq_bin} --version --no-color") { |io| io.read }.to_s
62           end
63         end
64
65         def initialize(url, root_url=nil, login=nil, password=nil, path_encoding=nil)
66           super
67           @path_encoding = path_encoding || 'UTF-8'
68           @flag_report_last_commit = SCM_GIT_REPORT_LAST_COMMIT
69         end
70
71         def info
72           begin
73             Info.new(:root_url => url, :lastrev => lastrev('',nil))
74           rescue
75             nil
76           end
77         end
78
79         def branches
80           return @branches if @branches
81           @branches = []
82           cmd = "#{self.class.sq_bin} --git-dir #{target('')} branch --no-color"
83           shellout(cmd) do |io|
84             io.each_line do |line|
85               @branches << line.match('\s*\*?\s*(.*)$')[1]
86             end
87           end
88           @branches.sort!
89         end
90
91         def tags
92           return @tags if @tags
93           cmd = "#{self.class.sq_bin} --git-dir #{target('')} tag"
94           shellout(cmd) do |io|
95             @tags = io.readlines.sort!.map{|t| t.strip}
96           end
97         end
98
99         def default_branch
100           branches.include?('master') ? 'master' : branches.first
101         end
102
103         def entries(path=nil, identifier=nil)
104           path ||= ''
105           entries = Entries.new
106           cmd = "#{self.class.sq_bin} --git-dir #{target('')} ls-tree -l "
107           cmd << shell_quote("HEAD:" + path) if identifier.nil?
108           cmd << shell_quote(identifier + ":" + path) if identifier
109           shellout(cmd)  do |io|
110             io.each_line do |line|
111               e = line.chomp.to_s
112               if e =~ /^\d+\s+(\w+)\s+([0-9a-f]{40})\s+([0-9-]+)\t(.+)$/
113                 type = $1
114                 sha = $2
115                 size = $3
116                 name = $4
117                 full_path = path.empty? ? name : "#{path}/#{name}"
118                 entries << Entry.new({:name => name,
119                  :path => full_path,
120                  :kind => (type == "tree") ? 'dir' : 'file',
121                  :size => (type == "tree") ? nil : size,
122                  :lastrev => @flag_report_last_commit ? lastrev(full_path,identifier) : Revision.new
123                 }) unless entries.detect{|entry| entry.name == name}
124               end
125             end
126           end
127           return nil if $? && $?.exitstatus != 0
128           entries.sort_by_name
129         end
130
131         def lastrev(path, rev)
132           return nil if path.nil?
133           cmd_args = %w|log --no-color --encoding=UTF-8 --date=iso --pretty=fuller --no-merges -n 1|
134           cmd_args << rev if rev 
135           cmd_args << "--" << path unless path.empty?
136           lines = []
137           scm_cmd(*cmd_args) { |io| lines = io.readlines }
138           begin
139               id = lines[0].split[1]
140               author = lines[1].match('Author:\s+(.*)$')[1]
141               time = Time.parse(lines[4].match('CommitDate:\s+(.*)$')[1])
142
143               Revision.new({
144                 :identifier => id,
145                 :scmid => id,
146                 :author => author, 
147                 :time => time,
148                 :message => nil, 
149                 :paths => nil 
150                 })
151           rescue NoMethodError => e
152               logger.error("The revision '#{path}' has a wrong format")
153               return nil
154           end
155         rescue ScmCommandAborted
156           nil
157         end
158
159         def revisions(path, identifier_from, identifier_to, options={})
160           revisions = Revisions.new
161           cmd_args = %w|log --no-color --encoding=UTF-8 --raw --date=iso --pretty=fuller|
162           cmd_args << "--reverse" if options[:reverse]
163           cmd_args << "--all" if options[:all]
164           cmd_args << "-n" << "#{options[:limit].to_i}" if options[:limit]
165           from_to = ""
166           from_to << "#{identifier_from}.." if identifier_from
167           from_to << "#{identifier_to}" if identifier_to
168           cmd_args << from_to if !from_to.empty?
169           cmd_args << "--since=#{options[:since].strftime("%Y-%m-%d %H:%M:%S")}" if options[:since]
170           cmd_args << "--" << path if path && !path.empty?
171
172           scm_cmd *cmd_args do |io|
173             files=[]
174             changeset = {}
175             parsing_descr = 0  #0: not parsing desc or files, 1: parsing desc, 2: parsing files
176
177             io.each_line do |line|
178               if line =~ /^commit ([0-9a-f]{40})$/
179                 key = "commit"
180                 value = $1
181                 if (parsing_descr == 1 || parsing_descr == 2)
182                   parsing_descr = 0
183                   revision = Revision.new({
184                     :identifier => changeset[:commit],
185                     :scmid => changeset[:commit],
186                     :author => changeset[:author],
187                     :time => Time.parse(changeset[:date]),
188                     :message => changeset[:description],
189                     :paths => files
190                   })
191                   if block_given?
192                     yield revision
193                   else
194                     revisions << revision
195                   end
196                   changeset = {}
197                   files = []
198                 end
199                 changeset[:commit] = $1
200               elsif (parsing_descr == 0) && line =~ /^(\w+):\s*(.*)$/
201                 key = $1
202                 value = $2
203                 if key == "Author"
204                   changeset[:author] = value
205                 elsif key == "CommitDate"
206                   changeset[:date] = value
207                 end
208               elsif (parsing_descr == 0) && line.chomp.to_s == ""
209                 parsing_descr = 1
210                 changeset[:description] = ""
211               elsif (parsing_descr == 1 || parsing_descr == 2) \
212                   && line =~ /^:\d+\s+\d+\s+[0-9a-f.]+\s+[0-9a-f.]+\s+(\w)\t(.+)$/
213                 parsing_descr = 2
214                 fileaction    = $1
215                 filepath      = $2
216                 p = scm_iconv('UTF-8', @path_encoding, filepath)
217                 files << {:action => fileaction, :path => p}
218               elsif (parsing_descr == 1 || parsing_descr == 2) \
219                   && line =~ /^:\d+\s+\d+\s+[0-9a-f.]+\s+[0-9a-f.]+\s+(\w)\d+\s+(\S+)\t(.+)$/
220                 parsing_descr = 2
221                 fileaction    = $1
222                 filepath      = $3
223                 p = scm_iconv('UTF-8', @path_encoding, filepath)
224                 files << {:action => fileaction, :path => p}
225               elsif (parsing_descr == 1) && line.chomp.to_s == ""
226                 parsing_descr = 2
227               elsif (parsing_descr == 1)
228                 changeset[:description] << line[4..-1]
229               end
230             end 
231
232             if changeset[:commit]
233               revision = Revision.new({
234                 :identifier => changeset[:commit],
235                 :scmid => changeset[:commit],
236                 :author => changeset[:author],
237                 :time => Time.parse(changeset[:date]),
238                 :message => changeset[:description],
239                 :paths => files
240               })
241
242               if block_given?
243                 yield revision
244               else
245                 revisions << revision
246               end
247             end
248           end
249           revisions
250         rescue ScmCommandAborted
251           revisions
252         end
253
254         def diff(path, identifier_from, identifier_to=nil)
255           path ||= ''
256
257           if identifier_to
258             cmd = "#{self.class.sq_bin} --git-dir #{target('')} diff --no-color #{shell_quote identifier_to} #{shell_quote identifier_from}" 
259           else
260             cmd = "#{self.class.sq_bin} --git-dir #{target('')} show --no-color #{shell_quote identifier_from}"
261           end
262
263           cmd << " -- #{shell_quote path}" unless path.empty?
264           diff = []
265           shellout(cmd) do |io|
266             io.each_line do |line|
267               diff << line
268             end
269           end
270           return nil if $? && $?.exitstatus != 0
271           diff
272         end
273         
274         def annotate(path, identifier=nil)
275           identifier = 'HEAD' if identifier.blank?
276           cmd = "#{self.class.sq_bin} --git-dir #{target('')} blame -p #{shell_quote identifier} -- #{shell_quote path}"
277           blame = Annotate.new
278           content = nil
279           shellout(cmd) { |io| io.binmode; content = io.read }
280           return nil if $? && $?.exitstatus != 0
281           # git annotates binary files
282           return nil if content.is_binary_data?
283           identifier = ''
284           # git shows commit author on the first occurrence only
285           authors_by_commit = {}
286           content.split("\n").each do |line|
287             if line =~ /^([0-9a-f]{39,40})\s.*/
288               identifier = $1
289             elsif line =~ /^author (.+)/
290               authors_by_commit[identifier] = $1.strip
291             elsif line =~ /^\t(.*)/
292               blame.add_line($1, Revision.new(:identifier => identifier, :author => authors_by_commit[identifier]))
293               identifier = ''
294               author = ''
295             end
296           end
297           blame
298         end
299
300         def cat(path, identifier=nil)
301           if identifier.nil?
302             identifier = 'HEAD'
303           end
304           cmd = "#{self.class.sq_bin} --git-dir #{target('')} show --no-color #{shell_quote(identifier + ':' + path)}"
305           cat = nil
306           shellout(cmd) do |io|
307             io.binmode
308             cat = io.read
309           end
310           return nil if $? && $?.exitstatus != 0
311           cat
312         end
313
314         class Revision < Redmine::Scm::Adapters::Revision
315           # Returns the readable identifier
316           def format_identifier
317             identifier[0,8]
318           end
319         end
320
321         def scm_cmd(*args, &block)
322           repo_path = root_url || url
323           full_args = [GIT_BIN, '--git-dir', repo_path]
324           full_args += args
325           ret = shellout(full_args.map { |e| shell_quote e.to_s }.join(' '), &block)
326           if $? && $?.exitstatus != 0
327             raise ScmCommandAborted, "git exited with non-zero status: #{$?.exitstatus}"
328           end
329           ret
330         end
331         private :scm_cmd
332       end
333     end
334   end
335 end