OSDN Git Service

scm: mercurial: change some newlines in mercurial_adapter.rb CRLF to LF.
[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 theversion.respond_to?(:force_encoding)
59               theversion.force_encoding('ASCII-8BIT')
60             end
61             if m = theversion.match(%r{\A(.*?)((\d+\.)+\d+)})
62               m[2].scan(%r{\d+}).collect(&:to_i)
63             end
64           end
65
66           def hgversion_from_command_line
67             shellout("#{sq_bin} --version") { |io| io.read }.to_s
68           end
69
70           def template_path
71             @@template_path ||= template_path_for(client_version)
72           end
73
74           def template_path_for(version)
75             if ((version <=> [0,9,5]) > 0) || version.empty?
76               ver = "1.0"
77             else
78               ver = "0.9.5"
79             end
80             "#{HELPERS_DIR}/#{TEMPLATE_NAME}-#{ver}.#{TEMPLATE_EXTENSION}"
81           end
82         end
83
84         def initialize(url, root_url=nil, login=nil, password=nil)
85           super
86           @path_encoding = 'UTF-8'
87         end
88
89         def info
90           tip = summary['repository']['tip']
91           Info.new(:root_url => CGI.unescape(summary['repository']['root']),
92                    :lastrev => Revision.new(:revision => tip['revision'],
93                                             :scmid => tip['node']))
94         end
95
96         def tags
97           as_ary(summary['repository']['tag']).map { |e| e['name'] }
98         end
99
100         # Returns map of {'tag' => 'nodeid', ...}
101         def tagmap
102           alist = as_ary(summary['repository']['tag']).map do |e|
103             e.values_at('name', 'node')
104           end
105           Hash[*alist.flatten]
106         end
107
108         def branches
109           as_ary(summary['repository']['branch']).map { |e| e['name'] }
110         end
111
112         # Returns map of {'branch' => 'nodeid', ...}
113         def branchmap
114           alist = as_ary(summary['repository']['branch']).map do |e|
115             e.values_at('name', 'node')
116           end
117           Hash[*alist.flatten]
118         end
119
120         def summary
121           return @summary if @summary 
122           hg 'rhsummary' do |io|
123             begin
124               @summary = ActiveSupport::XmlMini.parse(io.read)['rhsummary']
125             rescue
126             end
127           end
128         end
129         private :summary
130
131         def entries(path=nil, identifier=nil)
132           p1 = scm_iconv(@path_encoding, 'UTF-8', path)
133           manifest = hg('rhmanifest', '-r', hgrev(identifier),
134                         CGI.escape(without_leading_slash(p1.to_s))) do |io|
135             begin
136               ActiveSupport::XmlMini.parse(io.read)['rhmanifest']['repository']['manifest']
137             rescue
138             end
139           end
140           path_prefix = path.blank? ? '' : with_trailling_slash(path)
141
142           entries = Entries.new
143           as_ary(manifest['dir']).each do |e|
144             n = scm_iconv('UTF-8', @path_encoding, CGI.unescape(e['name']))
145             p = "#{path_prefix}#{n}"
146             entries << Entry.new(:name => n, :path => p, :kind => 'dir')
147           end
148
149           as_ary(manifest['file']).each do |e|
150             n = scm_iconv('UTF-8', @path_encoding, CGI.unescape(e['name']))
151             p = "#{path_prefix}#{n}"
152             lr = Revision.new(:revision => e['revision'], :scmid => e['node'],
153                               :identifier => e['node'],
154                               :time => Time.at(e['time'].to_i))
155             entries << Entry.new(:name => n, :path => p, :kind => 'file',
156                                  :size => e['size'].to_i, :lastrev => lr)
157           end
158
159           entries
160         rescue HgCommandAborted
161           nil  # means not found
162         end
163
164         def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={})
165           revs = Revisions.new
166           each_revision(path, identifier_from, identifier_to, options) { |e| revs << e }
167           revs
168         end
169
170         # Iterates the revisions by using a template file that
171         # makes Mercurial produce a xml output.
172         def each_revision(path=nil, identifier_from=nil, identifier_to=nil, options={})
173           hg_args = ['log', '--debug', '-C', '--style', self.class.template_path]
174           hg_args << '-r' << "#{hgrev(identifier_from)}:#{hgrev(identifier_to)}"
175           hg_args << '--limit' << options[:limit] if options[:limit]
176           hg_args << hgtarget(path) unless path.blank?
177           log = hg(*hg_args) do |io|
178             begin
179               # Mercurial < 1.5 does not support footer template for '</log>'
180               ActiveSupport::XmlMini.parse("#{io.read}</log>")['log']
181             rescue
182             end
183           end
184
185           as_ary(log['logentry']).each do |le|
186             cpalist = as_ary(le['paths']['path-copied']).map do |e|
187               [e['__content__'], e['copyfrom-path']].map { |s| CGI.unescape(s) }
188             end
189             cpmap = Hash[*cpalist.flatten]
190
191             paths = as_ary(le['paths']['path']).map do |e|
192               p = scm_iconv('UTF-8', @path_encoding, CGI.unescape(e['__content__']) )
193               {:action => e['action'], :path => with_leading_slash(p),
194                :from_path => (cpmap.member?(p) ? with_leading_slash(cpmap[p]) : nil),
195                :from_revision => (cpmap.member?(p) ? le['revision'] : nil)}
196             end.sort { |a, b| a[:path] <=> b[:path] }
197
198             yield Revision.new(:revision => le['revision'],
199                                :scmid => le['node'],
200                                :author => (le['author']['__content__'] rescue ''),
201                                :time => Time.parse(le['date']['__content__']).localtime,
202                                :message => le['msg']['__content__'],
203                                :paths => paths)
204           end
205           self
206         end
207
208         def diff(path, identifier_from, identifier_to=nil)
209           hg_args = %w|rhdiff|
210           if identifier_to
211             hg_args << '-r' << hgrev(identifier_to) << '-r' << hgrev(identifier_from)
212           else
213             hg_args << '-c' << hgrev(identifier_from)
214           end
215           unless path.blank?
216             p = scm_iconv(@path_encoding, 'UTF-8', path)
217             hg_args << CGI.escape(hgtarget(p))
218           end
219           diff = []
220           hg *hg_args do |io|
221             io.each_line do |line|
222               diff << line
223             end
224           end
225           diff
226         rescue HgCommandAborted
227           nil  # means not found
228         end
229
230         def cat(path, identifier=nil)
231           hg 'cat', '-r', hgrev(identifier), hgtarget(path) do |io|
232             io.binmode
233             io.read
234           end
235         rescue HgCommandAborted
236           nil  # means not found
237         end
238
239         def annotate(path, identifier=nil)
240           blame = Annotate.new
241           hg 'annotate', '-ncu', '-r', hgrev(identifier), hgtarget(path) do |io|
242             io.each_line do |line|
243               next unless line =~ %r{^([^:]+)\s(\d+)\s([0-9a-f]+):\s(.*)$}
244               r = Revision.new(:author => $1.strip, :revision => $2, :scmid => $3,
245                                :identifier => $3)
246               blame.add_line($4.rstrip, r)
247             end
248           end
249           blame
250         rescue HgCommandAborted
251           nil  # means not found or cannot be annotated
252         end
253
254         class Revision < Redmine::Scm::Adapters::Revision
255           # Returns the readable identifier
256           def format_identifier
257             "#{revision}:#{scmid}"
258           end
259         end
260
261         # Runs 'hg' command with the given args
262         def hg(*args, &block)
263           repo_path = root_url || url
264           full_args = [HG_BIN, '-R', repo_path, '--encoding', 'utf-8']
265           full_args << '--config' << "extensions.redminehelper=#{HG_HELPER_EXT}"
266           full_args << '--config' << 'diff.git=false'
267           full_args += args
268           ret = shellout(full_args.map { |e| shell_quote e.to_s }.join(' '), &block)
269           if $? && $?.exitstatus != 0
270             raise HgCommandAborted, "hg exited with non-zero status: #{$?.exitstatus}"
271           end
272           ret
273         end
274         private :hg
275
276         # Returns correct revision identifier
277         def hgrev(identifier, sq=false)
278           rev = identifier.blank? ? 'tip' : identifier.to_s
279           rev = shell_quote(rev) if sq
280           rev
281         end
282         private :hgrev
283
284         def hgtarget(path)
285           path ||= ''
286           root_url + '/' + without_leading_slash(path)
287         end
288         private :hgtarget
289
290         def as_ary(o)
291           return [] unless o
292           o.is_a?(Array) ? o : Array[o]
293         end
294         private :as_ary
295       end
296     end
297   end
298 end