1 # Redmine - project management software
2 # Copyright (C) 2006-2011 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 'uri'
20
21 module Redmine
22 module Scm
23 module Adapters
24 class SubversionAdapter < AbstractAdapter
25
26 # SVN executable name
27 SVN_BIN = Redmine::Configuration['scm_subversion_command'] || "svn"
28
29 class << self
30 def client_command
31 @@bin ||= SVN_BIN
32 end
33
34 def sq_bin
35 @@sq_bin ||= shell_quote_command
36 end
37
38 def client_version
39 @@client_version ||= (svn_binary_version || [])
40 end
41
42 def client_available
43 # --xml options are introduced in 1.3.
44 # http://subversion.apache.org/docs/release-notes/1.3.html
45 client_version_above?([1, 3])
46 end
47
48 def svn_binary_version
49 scm_version = scm_version_from_command_line.dup
50 if scm_version.respond_to?(:force_encoding)
51 scm_version.force_encoding('ASCII-8BIT')
52 end
53 if m = scm_version.match(%r{\A(.*?)((\d+\.)+\d+)})
54 m[2].scan(%r{\d+}).collect(&:to_i)
55 end
56 end
57
58 def scm_version_from_command_line
59 shellout("#{sq_bin} --version") { |io| io.read }.to_s
60 end
61 end
62
63 # Get info about the svn repository
64 def info
65 cmd = "#{self.class.sq_bin} info --xml #{target}"
66 cmd << credentials_string
67 info = nil
68 shellout(cmd) do |io|
69 output = io.read
70 if output.respond_to?(:force_encoding)
71 output.force_encoding('UTF-8')
72 end
73 begin
74 doc = ActiveSupport::XmlMini.parse(output)
75 # root_url = doc.elements["info/entry/repository/root"].text
76 info = Info.new({:root_url => doc['info']['entry']['repository']['root']['__content__'],
77 :lastrev => Revision.new({
78 :identifier => doc['info']['entry']['commit']['revision'],
79 :time => Time.parse(doc['info']['entry']['commit']['date']['__content__']).localtime,
80 :author => (doc['info']['entry']['commit']['author'] ? doc['info']['entry']['commit']['author']['__content__'] : "")
81 })
82 })
83 rescue
84 end
85 end
86 return nil if $? && $?.exitstatus != 0
87 info
88 rescue CommandFailed
89 return nil
90 end
91
92 # Returns an Entries collection
93 # or nil if the given path doesn't exist in the repository
94 def entries(path=nil, identifier=nil, options={})
95 path ||= ''
96 identifier = (identifier and identifier.to_i > 0) ? identifier.to_i : "HEAD"
97 entries = Entries.new
98 cmd = "#{self.class.sq_bin} list --xml #{target(path)}@#{identifier}"
99 cmd << credentials_string
100 shellout(cmd) do |io|
101 output = io.read
102 if output.respond_to?(:force_encoding)
103 output.force_encoding('UTF-8')
104 end
105 begin
106 doc = ActiveSupport::XmlMini.parse(output)
107 each_xml_element(doc['lists']['list'], 'entry') do |entry|
108 commit = entry['commit']
109 commit_date = commit['date']
110 # Skip directory if there is no commit date (usually that
111 # means that we don't have read access to it)
112 next if entry['kind'] == 'dir' && commit_date.nil?
113 name = entry['name']['__content__']
114 entries << Entry.new({:name => URI.unescape(name),
115 :path => ((path.empty? ? "" : "#{path}/") + name),
116 :kind => entry['kind'],
117 :size => ((s = entry['size']) ? s['__content__'].to_i : nil),
118 :lastrev => Revision.new({
119 :identifier => commit['revision'],
120 :time => Time.parse(commit_date['__content__'].to_s).localtime,
121 :author => ((a = commit['author']) ? a['__content__'] : nil)
122 })
123 })
124 end
125 rescue Exception => e
126 logger.error("Error parsing svn output: #{e.message}")
127 logger.error("Output was:\n #{output}")
128 end
129 end
130 return nil if $? && $?.exitstatus != 0
131 logger.debug("Found #{entries.size} entries in the repository for #{target(path)}") if logger && logger.debug?
132 entries.sort_by_name
133 end
134
135 def properties(path, identifier=nil)
136 # proplist xml output supported in svn 1.5.0 and higher
137 return nil unless self.class.client_version_above?([1, 5, 0])
138
139 identifier = (identifier and identifier.to_i > 0) ? identifier.to_i : "HEAD"
140 cmd = "#{self.class.sq_bin} proplist --verbose --xml #{target(path)}@#{identifier}"
141 cmd << credentials_string
142 properties = {}
143 shellout(cmd) do |io|
144 output = io.read
145 if output.respond_to?(:force_encoding)
146 output.force_encoding('UTF-8')
147 end
148 begin
149 doc = ActiveSupport::XmlMini.parse(output)
150 each_xml_element(doc['properties']['target'], 'property') do |property|
151 properties[ property['name'] ] = property['__content__'].to_s
152 end
153 rescue
154 end
155 end
156 return nil if $? && $?.exitstatus != 0
157 properties
158 end
159
160 def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={})
161 path ||= ''
162 identifier_from = (identifier_from && identifier_from.to_i > 0) ? identifier_from.to_i : "HEAD"
163 identifier_to = (identifier_to && identifier_to.to_i > 0) ? identifier_to.to_i : 1
164 revisions = Revisions.new
165 cmd = "#{self.class.sq_bin} log --xml -r #{identifier_from}:#{identifier_to}"
166 cmd << credentials_string
167 cmd << " --verbose " if options[:with_paths]
168 cmd << " --limit #{options[:limit].to_i}" if options[:limit]
169 cmd << ' ' + target(path)
170 shellout(cmd) do |io|
171 output = io.read
172 if output.respond_to?(:force_encoding)
173 output.force_encoding('UTF-8')
174 end
175 begin
176 doc = ActiveSupport::XmlMini.parse(output)
177 each_xml_element(doc['log'], 'logentry') do |logentry|
178 paths = []
179 each_xml_element(logentry['paths'], 'path') do |path|
180 paths << {:action => path['action'],
181 :path => path['__content__'],
182 :from_path => path['copyfrom-path'],
183 :from_revision => path['copyfrom-rev']
184 }
185 end if logentry['paths'] && logentry['paths']['path']
186 paths.sort! { |x,y| x[:path] <=> y[:path] }
187
188 revisions << Revision.new({:identifier => logentry['revision'],
189 :author => (logentry['author'] ? logentry['author']['__content__'] : ""),
190 :time => Time.parse(logentry['date']['__content__'].to_s).localtime,
191 :message => logentry['msg']['__content__'],
192 :paths => paths
193 })
194 end
195 rescue
196 end
197 end
198 return nil if $? && $?.exitstatus != 0
199 revisions
200 end
201
202 def diff(path, identifier_from, identifier_to=nil)
203 path ||= ''
204 identifier_from = (identifier_from and identifier_from.to_i > 0) ? identifier_from.to_i : ''
205
206 identifier_to = (identifier_to and identifier_to.to_i > 0) ? identifier_to.to_i : (identifier_from.to_i - 1)
207
208 cmd = "#{self.class.sq_bin} diff -r "
209 cmd << "#{identifier_to}:"
210 cmd << "#{identifier_from}"
211 cmd << " #{target(path)}@#{identifier_from}"
212 cmd << credentials_string
213 diff = []
214 shellout(cmd) do |io|
215 io.each_line do |line|
216 diff << line
217 end
218 end
219 return nil if $? && $?.exitstatus != 0
220 diff
221 end
222
223 def cat(path, identifier=nil)
224 identifier = (identifier and identifier.to_i > 0) ? identifier.to_i : "HEAD"
225 cmd = "#{self.class.sq_bin} cat #{target(path)}@#{identifier}"
226 cmd << credentials_string
227 cat = nil
228 shellout(cmd) do |io|
229 io.binmode
230 cat = io.read
231 end
232 return nil if $? && $?.exitstatus != 0
233 cat
234 end
235
236 def annotate(path, identifier=nil)
237 identifier = (identifier and identifier.to_i > 0) ? identifier.to_i : "HEAD"
238 cmd = "#{self.class.sq_bin} blame #{target(path)}@#{identifier}"
239 cmd << credentials_string
240 blame = Annotate.new
241 shellout(cmd) do |io|
242 io.each_line do |line|
243 next unless line =~ %r{^\s*(\d+)\s*(\S+)\s(.*)$}
244 rev = $1
245 blame.add_line($3.rstrip,
246 Revision.new(
247 :identifier => rev,
248 :revision => rev,
249 :author => $2.strip
250 ))
251 end
252 end
253 return nil if $? && $?.exitstatus != 0
254 blame
255 end
256
257 private
258
259 def credentials_string
260 str = ''
261 str << " --username #{shell_quote(@login)}" unless @login.blank?
262 str << " --password #{shell_quote(@password)}" unless @login.blank? || @password.blank?
263 str << " --no-auth-cache --non-interactive"
264 str
265 end
266
267 # Helper that iterates over the child elements of a xml node
268 # MiniXml returns a hash when a single child is found
269 # or an array of hashes for multiple children
270 def each_xml_element(node, name)
271 if node && node[name]
272 if node[name].is_a?(Hash)
273 yield node[name]
274 else
275 node[name].each do |element|
276 yield element
277 end
278 end
279 end
280 end
281
282 def target(path = '')
283 base = path.match(/^\//) ? root_url : url
284 uri = "#{base}/#{path}"
285 uri = URI.escape(URI.escape(uri), '[]')
286 shell_quote(uri.gsub(/[?<>\*]/, ''))
287 end
288 end
289 end
290 end
291 end