OSDN Git Service

scm: mercurial: fix Ruby 1.9 "hg diff" test fails (#7518).
[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           tip = summary['repository']['tip']
83           Info.new(:root_url => CGI.unescape(summary['repository']['root']),
84                    :lastrev => Revision.new(:revision => tip['revision'],
85                                             :scmid => tip['node']))
86         end
87
88         def summary
89           @summary ||= hg 'rhsummary' do |io|
90             ActiveSupport::XmlMini.parse(io.read)['rhsummary']
91           end
92         end
93         private :summary
94
95         def entries(path=nil, identifier=nil)
96           manifest = hg('rhmanifest', '-r', hgrev(identifier),
97                         CGI.escape(without_leading_slash(path.to_s))) do |io|
98             ActiveSupport::XmlMini.parse(io.read)['rhmanifest']['repository']['manifest']
99           end
100           path_prefix = path.blank? ? '' : with_trailling_slash(path)
101
102           entries = Entries.new
103           as_ary(manifest['dir']).each do |e|
104             n = CGI.unescape(e['name'])
105             p = "#{path_prefix}#{n}"
106             entries << Entry.new(:name => n, :path => p, :kind => 'dir')
107           end
108
109           as_ary(manifest['file']).each do |e|
110             n = CGI.unescape(e['name'])
111             p = "#{path_prefix}#{n}"
112             lr = Revision.new(:revision => e['revision'], :scmid => e['node'],
113                               :identifier => e['node'],
114                               :time => Time.at(e['time'].to_i))
115             entries << Entry.new(:name => n, :path => p, :kind => 'file',
116                                  :size => e['size'].to_i, :lastrev => lr)
117           end
118
119           entries
120         rescue HgCommandAborted
121           nil  # means not found
122         end
123
124         def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={})
125           revs = Revisions.new
126           each_revision(path, identifier_from, identifier_to, options) { |e| revs << e }
127           revs
128         end
129
130         # Iterates the revisions by using a template file that
131         # makes Mercurial produce a xml output.
132         def each_revision(path=nil, identifier_from=nil, identifier_to=nil, options={})
133           hg_args = ['log', '--debug', '-C', '--style', self.class.template_path]
134           hg_args << '-r' << "#{hgrev(identifier_from)}:#{hgrev(identifier_to)}"
135           hg_args << '--limit' << options[:limit] if options[:limit]
136           hg_args << hgtarget(path) unless path.blank?
137           log = hg(*hg_args) do |io|
138             # Mercurial < 1.5 does not support footer template for '</log>'
139             ActiveSupport::XmlMini.parse("#{io.read}</log>")['log']
140           end
141
142           as_ary(log['logentry']).each do |le|
143             cpalist = as_ary(le['paths']['path-copied']).map do |e|
144               [e['__content__'], e['copyfrom-path']].map { |s| CGI.unescape(s) }
145             end
146             cpmap = Hash[*cpalist.flatten]
147
148             paths = as_ary(le['paths']['path']).map do |e|
149               p = CGI.unescape(e['__content__'])
150               {:action => e['action'], :path => with_leading_slash(p),
151                :from_path => (cpmap.member?(p) ? with_leading_slash(cpmap[p]) : nil),
152                :from_revision => (cpmap.member?(p) ? le['revision'] : nil)}
153             end.sort { |a, b| a[:path] <=> b[:path] }
154
155             yield Revision.new(:revision => le['revision'],
156                                :scmid => le['node'],
157                                :author => (le['author']['__content__'] rescue ''),
158                                :time => Time.parse(le['date']['__content__']).localtime,
159                                :message => le['msg']['__content__'],
160                                :paths => paths)
161           end
162           self
163         end
164
165         def diff(path, identifier_from, identifier_to=nil)
166           hg_args = %w|rhdiff|
167           if identifier_to
168             hg_args << '-r' << hgrev(identifier_to) << '-r' << hgrev(identifier_from)
169           else
170             hg_args << '-c' << hgrev(identifier_from)
171           end
172           hg_args << CGI.escape(hgtarget(path)) unless path.blank?
173           diff = []
174           hg *hg_args do |io|
175             io.each_line do |line|
176               diff << line
177             end
178           end
179           diff
180         rescue HgCommandAborted
181           nil  # means not found
182         end
183
184         def cat(path, identifier=nil)
185           hg 'cat', '-r', hgrev(identifier), hgtarget(path) do |io|
186             io.binmode
187             io.read
188           end
189         rescue HgCommandAborted
190           nil  # means not found
191         end
192
193         def annotate(path, identifier=nil)
194           blame = Annotate.new
195           hg 'annotate', '-ncu', '-r', hgrev(identifier), hgtarget(path) do |io|
196             io.each_line do |line|
197               next unless line =~ %r{^([^:]+)\s(\d+)\s([0-9a-f]+):\s(.*)$}
198               r = Revision.new(:author => $1.strip, :revision => $2, :scmid => $3,
199                                :identifier => $3)
200               blame.add_line($4.rstrip, r)
201             end
202           end
203           blame
204         rescue HgCommandAborted
205           nil  # means not found or cannot be annotated
206         end
207
208         class Revision < Redmine::Scm::Adapters::Revision
209           # Returns the readable identifier
210           def format_identifier
211             "#{revision}:#{scmid}"
212           end
213         end
214
215         # Runs 'hg' command with the given args
216         def hg(*args, &block)
217           repo_path = root_url || url
218           full_args = [HG_BIN, '-R', repo_path, '--encoding', 'utf-8']
219           full_args << '--config' << "extensions.redminehelper=#{HG_HELPER_EXT}"
220           full_args << '--config' << 'diff.git=false'
221           full_args += args
222           ret = shellout(full_args.map { |e| shell_quote e.to_s }.join(' '), &block)
223           if $? && $?.exitstatus != 0
224             raise HgCommandAborted, "hg exited with non-zero status: #{$?.exitstatus}"
225           end
226           ret
227         end
228         private :hg
229
230         # Returns correct revision identifier
231         def hgrev(identifier, sq=false)
232           rev = identifier.blank? ? 'tip' : identifier.to_s
233           rev = shell_quote(rev) if sq
234           rev
235         end
236         private :hgrev
237
238         def hgtarget(path)
239           path ||= ''
240           root_url + '/' + without_leading_slash(path)
241         end
242         private :hgtarget
243
244         def as_ary(o)
245           return [] unless o
246           o.is_a?(Array) ? o : Array[o]
247         end
248         private :as_ary
249       end
250     end
251   end
252 end