OSDN Git Service

6024a52a865c1d4d56e5ba9a45aa9c1770a3b2b8
[redminele/redmine.git] / lib / redmine / scm / adapters / mercurial_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 require 'cgi'
20
21 module Redmine
22   module Scm
23     module Adapters
24       class MercurialAdapter < AbstractAdapter
25
26         # Mercurial executable name
27         HG_BIN = Redmine::Configuration['scm_mercurial_command'] || "hg"
28         HELPERS_DIR = File.dirname(__FILE__) + "/mercurial"
29         HG_HELPER_EXT = "#{HELPERS_DIR}/redminehelper.py"
30         TEMPLATE_NAME = "hg-template"
31         TEMPLATE_EXTENSION = "tmpl"
32
33         # raised if hg command exited with error, e.g. unknown revision.
34         class HgCommandAborted < CommandFailed; end
35
36         class << self
37           def client_command
38             @@bin    ||= HG_BIN
39           end
40
41           def sq_bin
42             @@sq_bin ||= shell_quote(HG_BIN)
43           end
44
45           def client_version
46             @@client_version ||= (hgversion || [])
47           end
48
49           def client_available
50             !client_version.empty?
51           end
52
53           def hgversion
54             # The hg version is expressed either as a
55             # release number (eg 0.9.5 or 1.0) or as a revision
56             # id composed of 12 hexa characters.
57             theversion = hgversion_from_command_line
58             if m = theversion.match(%r{\A(.*?)((\d+\.)+\d+)})
59               m[2].scan(%r{\d+}).collect(&:to_i)
60             end
61           end
62
63           def hgversion_from_command_line
64             shellout("#{sq_bin} --version") { |io| io.read }.to_s
65           end
66
67           def template_path
68             @@template_path ||= template_path_for(client_version)
69           end
70
71           def template_path_for(version)
72             if ((version <=> [0,9,5]) > 0) || version.empty?
73               ver = "1.0"
74             else
75               ver = "0.9.5"
76             end
77             "#{HELPERS_DIR}/#{TEMPLATE_NAME}-#{ver}.#{TEMPLATE_EXTENSION}"
78           end
79         end
80
81         def info
82           cmd = "#{self.class.sq_bin} -R #{target('')} root"
83           root_url = nil
84           shellout(cmd) do |io|
85             root_url = io.read
86           end
87           return nil if $? && $?.exitstatus != 0
88           info = Info.new({:root_url => root_url.chomp,
89                             :lastrev => revisions(nil,nil,nil,{:limit => 1}).last
90                           })
91           info
92         rescue CommandFailed
93           return nil
94         end
95
96         def summary
97           @summary ||= hg 'rhsummary' do |io|
98             ActiveSupport::XmlMini.parse(io.read)['rhsummary']
99           end
100         end
101         private :summary
102
103         def entries(path=nil, identifier=nil)
104           path ||= ''
105           entries = Entries.new
106           cmd = "#{self.class.sq_bin} -R #{target('')} --cwd #{target('')} locate"
107           cmd << " -r #{hgrev(identifier, true)}"
108           cmd << " " + shell_quote("path:#{path}") unless path.empty?
109           shellout(cmd) do |io|
110             io.each_line do |line|
111               # HG uses antislashs as separator on Windows
112               line = line.gsub(/\\/, "/")
113               if path.empty? or e = line.gsub!(%r{^#{with_trailling_slash(path)}},'')
114                 e ||= line
115                 e = e.chomp.split(%r{[\/\\]})
116                 entries << Entry.new({:name => e.first,
117                                        :path => (path.nil? or path.empty? ? e.first : "#{with_trailling_slash(path)}#{e.first}"),
118                                        :kind => (e.size > 1 ? 'dir' : 'file'),
119                                        :lastrev => Revision.new
120                                      }) unless e.empty? || entries.detect{|entry| entry.name == e.first}
121               end
122             end
123           end
124           return nil if $? && $?.exitstatus != 0
125           entries.sort_by_name
126         end
127
128         # Fetch the revisions by using a template file that 
129         # makes Mercurial produce a xml output.
130         def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={})  
131           revisions = Revisions.new
132           cmd = "#{self.class.sq_bin} --debug --encoding utf8 -R #{target('')} log -C --style #{shell_quote self.class.template_path}"
133           if identifier_from && identifier_to
134             cmd << " -r #{hgrev(identifier_from, true)}:#{hgrev(identifier_to, true)}"
135           elsif identifier_from
136             cmd << " -r #{hgrev(identifier_from, true)}:"
137           end
138           cmd << " --limit #{options[:limit].to_i}" if options[:limit]
139           cmd << " #{shell_quote path}" unless path.blank?
140           shellout(cmd) do |io|
141             begin
142               # HG doesn't close the XML Document...
143               doc = REXML::Document.new(io.read << "</log>")
144               doc.elements.each("log/logentry") do |logentry|
145                 paths = []
146                 copies = logentry.get_elements('paths/path-copied')
147                 logentry.elements.each("paths/path") do |path|
148                   # Detect if the added file is a copy
149                   if path.attributes['action'] == 'A' and c = copies.find{ |e| e.text == path.text }
150                     from_path = c.attributes['copyfrom-path']
151                     from_rev = logentry.attributes['revision']
152                   end
153                   paths << {:action => path.attributes['action'],
154                     :path => "/#{CGI.unescape(path.text)}",
155                     :from_path => from_path ? "/#{CGI.unescape(from_path)}" : nil,
156                     :from_revision => from_rev ? from_rev : nil
157                   }
158                 end
159                 paths.sort! { |x,y| x[:path] <=> y[:path] }
160
161                 revisions << Revision.new({:identifier => logentry.attributes['revision'],
162                                             :scmid => logentry.attributes['node'],
163                                             :author => (logentry.elements['author'] ? logentry.elements['author'].text : ""),
164                                             :time => Time.parse(logentry.elements['date'].text).localtime,
165                                             :message => logentry.elements['msg'].text,
166                                             :paths => paths
167                                           })
168               end
169             rescue
170               logger.debug($!)
171             end
172           end
173           return nil if $? && $?.exitstatus != 0
174           revisions
175         end
176
177         def diff(path, identifier_from, identifier_to=nil)
178           path ||= ''
179           diff_args = ''
180           diff = []
181           if identifier_to
182             diff_args = "-r #{hgrev(identifier_to, true)} -r #{hgrev(identifier_from, true)}"
183           else
184             if self.class.client_version_above?([1, 2])
185               diff_args = "-c #{hgrev(identifier_from, true)}"
186             else
187               return []
188             end
189           end
190           cmd = "#{self.class.sq_bin} -R #{target('')} --config diff.git=false diff --nodates #{diff_args}"
191           cmd << " -I #{target(path)}" unless path.empty?
192           shellout(cmd) do |io|
193             io.each_line do |line|
194               diff << line
195             end
196           end
197           return nil if $? && $?.exitstatus != 0
198           diff
199         end
200
201         def cat(path, identifier=nil)
202           hg 'cat', '-r', hgrev(identifier), hgtarget(path) do |io|
203             io.binmode
204             io.read
205           end
206         rescue HgCommandAborted
207           nil  # means not found
208         end
209
210         def annotate(path, identifier=nil)
211           blame = Annotate.new
212           hg 'annotate', '-ncu', '-r', hgrev(identifier), hgtarget(path) do |io|
213             io.each_line do |line|
214               next unless line =~ %r{^([^:]+)\s(\d+)\s([0-9a-f]+):\s(.*)$}
215               r = Revision.new(:author => $1.strip, :revision => $2, :scmid => $3,
216                                :identifier => $3)
217               blame.add_line($4.rstrip, r)
218             end
219           end
220           blame
221         rescue HgCommandAborted
222           nil  # means not found or cannot be annotated
223         end
224
225         class Revision < Redmine::Scm::Adapters::Revision
226           # Returns the readable identifier
227           def format_identifier
228             "#{revision}:#{scmid}"
229           end
230         end
231
232         # Runs 'hg' command with the given args
233         def hg(*args, &block)
234           repo_path = root_url || url
235           full_args = [HG_BIN, '-R', repo_path, '--encoding', 'utf-8']
236           full_args << '--config' << "extensions.redminehelper=#{HG_HELPER_EXT}"
237           full_args << '--config' << 'diff.git=false'
238           full_args += args
239           ret = shellout(full_args.map { |e| shell_quote e.to_s }.join(' '), &block)
240           if $? && $?.exitstatus != 0
241             raise HgCommandAborted, "hg exited with non-zero status: #{$?.exitstatus}"
242           end
243           ret
244         end
245         private :hg
246
247         # Returns correct revision identifier
248         def hgrev(identifier, sq=false)
249           rev = identifier.blank? ? 'tip' : identifier.to_s
250           rev = shell_quote(rev) if sq
251           rev
252         end
253         private :hgrev
254
255         def hgtarget(path)
256           path ||= ''
257           root_url + '/' + without_leading_slash(path)
258         end
259         private :hgtarget
260       end
261     end
262   end
263 end