OSDN Git Service

scm: add "options" parameter in adapter entries().
[redminele/redmine.git] / lib / redmine / scm / adapters / cvs_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 CvsAdapter < AbstractAdapter
24
25         # CVS executable name
26         CVS_BIN = Redmine::Configuration['scm_cvs_command'] || "cvs"
27
28         # raised if scm command exited with error, e.g. unknown revision.
29         class ScmCommandAborted < CommandFailed; end
30
31         class << self
32           def client_command
33             @@bin    ||= CVS_BIN
34           end
35
36           def sq_bin
37             @@sq_bin ||= shell_quote(CVS_BIN)
38           end
39
40           def client_version
41             @@client_version ||= (scm_command_version || [])
42           end
43
44           def client_available
45             client_version_above?([1, 12])
46           end
47
48           def scm_command_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+)}m)
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         # Guidelines for the input:
64         #  url      -> the project-path, relative to the cvsroot (eg. module name)
65         #  root_url -> the good old, sometimes damned, CVSROOT
66         #  login    -> unnecessary
67         #  password -> unnecessary too
68         def initialize(url, root_url=nil, login=nil, password=nil,
69                        path_encoding=nil)
70           @path_encoding = path_encoding.blank? ? 'UTF-8' : path_encoding
71           @url      = url
72           # TODO: better Exception here (IllegalArgumentException)
73           raise CommandFailed if root_url.blank?
74           @root_url  = root_url
75
76           # These are unused.
77           @login    = login if login && !login.empty?
78           @password = (password || "") if @login
79         end
80
81         def info
82           logger.debug "<cvs> info"
83           Info.new({:root_url => @root_url, :lastrev => nil})
84         end
85
86         def get_previous_revision(revision)
87           CvsRevisionHelper.new(revision).prevRev
88         end
89
90         # Returns an Entries collection
91         # or nil if the given path doesn't exist in the repository
92         # this method is used by the repository-browser (aka LIST)
93         def entries(path=nil, identifier=nil, options={})
94           logger.debug "<cvs> entries '#{path}' with identifier '#{identifier}'"
95           path_locale = scm_iconv(@path_encoding, 'UTF-8', path)
96           path_locale.force_encoding("ASCII-8BIT") if path_locale.respond_to?(:force_encoding)
97           entries = Entries.new
98           cmd_args = %w|-q rls -e|
99           cmd_args << "-D" << time_to_cvstime_rlog(identifier) if identifier
100           cmd_args << path_with_proj(path)
101           scm_cmd(*cmd_args) do |io|
102             io.each_line() do |line|
103               fields = line.chop.split('/',-1)
104               logger.debug(">>InspectLine #{fields.inspect}")
105               if fields[0]!="D"
106                 time = nil
107                 # Thu Dec 13 16:27:22 2007
108                 time_l = fields[-3].split(' ')
109                 if time_l.size == 5 && time_l[4].length == 4
110                   begin
111                     time = Time.parse(
112                              "#{time_l[1]} #{time_l[2]} #{time_l[3]} GMT #{time_l[4]}")
113                   rescue
114                   end
115                 end
116                 entries << Entry.new(
117                  {
118                   :name => scm_iconv('UTF-8', @path_encoding, fields[-5]),
119                   #:path => fields[-4].include?(path)?fields[-4]:(path + "/"+ fields[-4]),
120                   :path => scm_iconv('UTF-8', @path_encoding, "#{path_locale}/#{fields[-5]}"),
121                   :kind => 'file',
122                   :size => nil,
123                   :lastrev => Revision.new(
124                       {
125                         :revision => fields[-4],
126                         :name     => scm_iconv('UTF-8', @path_encoding, fields[-4]),
127                         :time     => time,
128                         :author   => ''
129                       })
130                   })
131               else
132                 entries << Entry.new(
133                  {
134                   :name    => scm_iconv('UTF-8', @path_encoding, fields[1]),
135                   :path    => scm_iconv('UTF-8', @path_encoding, "#{path_locale}/#{fields[1]}"),
136                   :kind    => 'dir',
137                   :size    => nil,
138                   :lastrev => nil
139                  })
140               end
141             end
142           end
143           entries.sort_by_name
144         rescue ScmCommandAborted
145           nil
146         end
147
148         STARTLOG="----------------------------"
149         ENDLOG  ="============================================================================="
150
151         # Returns all revisions found between identifier_from and identifier_to
152         # in the repository. both identifier have to be dates or nil.
153         # these method returns nothing but yield every result in block
154         def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={}, &block)
155           path_with_project_utf8   = path_with_proj(path)
156           path_with_project_locale = scm_iconv(@path_encoding, 'UTF-8', path_with_project_utf8)
157           logger.debug "<cvs> revisions path:" +
158               "'#{path}',identifier_from #{identifier_from}, identifier_to #{identifier_to}"
159           cmd_args = %w|-q rlog|
160           cmd_args << "-d" << ">#{time_to_cvstime_rlog(identifier_from)}" if identifier_from
161           cmd_args << path_with_project_utf8
162           scm_cmd(*cmd_args) do |io|
163             state      = "entry_start"
164             commit_log = String.new
165             revision   = nil
166             date       = nil
167             author     = nil
168             entry_path = nil
169             entry_name = nil
170             file_state = nil
171             branch_map = nil
172             io.each_line() do |line|
173               if state != "revision" && /^#{ENDLOG}/ =~ line
174                 commit_log = String.new
175                 revision   = nil
176                 state      = "entry_start"
177               end
178               if state == "entry_start"
179                 branch_map = Hash.new
180                 if /^RCS file: #{Regexp.escape(root_url_path)}\/#{Regexp.escape(path_with_project_locale)}(.+),v$/ =~ line
181                   entry_path = normalize_cvs_path($1)
182                   entry_name = normalize_path(File.basename($1))
183                   logger.debug("Path #{entry_path} <=> Name #{entry_name}")
184                 elsif /^head: (.+)$/ =~ line
185                   entry_headRev = $1 #unless entry.nil?
186                 elsif /^symbolic names:/ =~ line
187                   state = "symbolic" #unless entry.nil?
188                 elsif /^#{STARTLOG}/ =~ line
189                   commit_log = String.new
190                   state      = "revision"
191                 end
192                 next
193               elsif state == "symbolic"
194                 if /^(.*):\s(.*)/ =~ (line.strip)
195                   branch_map[$1] = $2
196                 else
197                   state = "tags"
198                   next
199                 end
200               elsif state == "tags"
201                 if /^#{STARTLOG}/ =~ line
202                   commit_log = ""
203                   state = "revision"
204                 elsif /^#{ENDLOG}/ =~ line
205                   state = "head"
206                 end
207                 next
208               elsif state == "revision"
209                 if /^#{ENDLOG}/ =~ line || /^#{STARTLOG}/ =~ line
210                   if revision
211                     revHelper = CvsRevisionHelper.new(revision)
212                     revBranch = "HEAD"
213                     branch_map.each() do |branch_name, branch_point|
214                       if revHelper.is_in_branch_with_symbol(branch_point)
215                         revBranch = branch_name
216                       end
217                     end
218                     logger.debug("********** YIELD Revision #{revision}::#{revBranch}")
219                     yield Revision.new({
220                       :time    => date,
221                       :author  => author,
222                       :message => commit_log.chomp,
223                       :paths => [{
224                         :revision => revision,
225                         :branch   => revBranch,
226                         :path     => scm_iconv('UTF-8', @path_encoding, entry_path),
227                         :name     => scm_iconv('UTF-8', @path_encoding, entry_name),
228                         :kind     => 'file',
229                         :action   => file_state
230                            }]
231                          })
232                   end
233                   commit_log = String.new
234                   revision   = nil
235                   if /^#{ENDLOG}/ =~ line
236                     state = "entry_start"
237                   end
238                   next
239                 end
240
241                 if /^branches: (.+)$/ =~ line
242                   # TODO: version.branch = $1
243                 elsif /^revision (\d+(?:\.\d+)+).*$/ =~ line
244                   revision = $1
245                 elsif /^date:\s+(\d+.\d+.\d+\s+\d+:\d+:\d+)/ =~ line
246                   date       = Time.parse($1)
247                   line_utf8    = scm_iconv('UTF-8', options[:log_encoding], line)
248                   author_utf8  = /author: ([^;]+)/.match(line_utf8)[1]
249                   author       = scm_iconv(options[:log_encoding], 'UTF-8', author_utf8)
250                   file_state   = /state: ([^;]+)/.match(line)[1]
251                   # TODO:
252                   #    linechanges only available in CVS....
253                   #    maybe a feature our SVN implementation.
254                   #    I'm sure, they are useful for stats or something else
255                   #                linechanges =/lines: \+(\d+) -(\d+)/.match(line)
256                   #                unless linechanges.nil?
257                   #                  version.line_plus  = linechanges[1]
258                   #                  version.line_minus = linechanges[2]
259                   #                else
260                   #                  version.line_plus  = 0
261                   #                  version.line_minus = 0
262                   #                end
263                 else
264                   commit_log << line unless line =~ /^\*\*\* empty log message \*\*\*/
265                 end
266               end
267             end
268           end
269         rescue ScmCommandAborted
270           Revisions.new
271         end
272
273         def diff(path, identifier_from, identifier_to=nil)
274           logger.debug "<cvs> diff path:'#{path}'" +
275               ",identifier_from #{identifier_from}, identifier_to #{identifier_to}"
276           cmd_args = %w|rdiff -u|
277           cmd_args << "-r#{identifier_to}"
278           cmd_args << "-r#{identifier_from}"
279           cmd_args << path_with_proj(path)
280           diff = []
281           scm_cmd(*cmd_args) do |io|
282             io.each_line do |line|
283               diff << line
284             end
285           end
286           diff
287         rescue ScmCommandAborted
288           nil
289         end
290
291         def cat(path, identifier=nil)
292           identifier = (identifier) ? identifier : "HEAD"
293           logger.debug "<cvs> cat path:'#{path}',identifier #{identifier}"
294           cmd_args = %w|-q co|
295           cmd_args << "-D" << time_to_cvstime(identifier) if identifier
296           cmd_args << "-p" << path_with_proj(path)
297           cat = nil
298           scm_cmd(*cmd_args) do |io|
299             io.binmode
300             cat = io.read
301           end
302           cat
303         rescue ScmCommandAborted
304           nil
305         end
306
307         def annotate(path, identifier=nil)
308           identifier = (identifier) ? identifier : "HEAD"
309           logger.debug "<cvs> annotate path:'#{path}',identifier #{identifier}"
310           cmd_args = %w|rannotate|
311           cmd_args << "-D" << time_to_cvstime(identifier) if identifier
312           cmd_args << path_with_proj(path)
313           blame = Annotate.new
314           scm_cmd(*cmd_args) do |io|
315             io.each_line do |line|
316               next unless line =~ %r{^([\d\.]+)\s+\(([^\)]+)\s+[^\)]+\):\s(.*)$}
317               blame.add_line(
318                   $3.rstrip,
319                   Revision.new(
320                     :revision   => $1,
321                     :identifier => nil,
322                     :author     => $2.strip
323                     ))
324             end
325           end
326           blame
327         rescue ScmCommandAborted
328           Annotate.new
329         end
330
331         private
332
333         # Returns the root url without the connexion string
334         # :pserver:anonymous@foo.bar:/path => /path
335         # :ext:cvsservername:/path => /path
336         def root_url_path
337           root_url.to_s.gsub(/^:.+:\d*/, '')
338         end
339
340         # convert a date/time into the CVS-format
341         def time_to_cvstime(time)
342           return nil if time.nil?
343           time = Time.now if time == 'HEAD'
344
345           unless time.kind_of? Time
346             time = Time.parse(time)
347           end
348           return time_to_cvstime_rlog(time)
349         end
350
351         def time_to_cvstime_rlog(time)
352           return nil if time.nil?
353           t1 = time.clone.localtime
354           return t1.strftime("%Y-%m-%d %H:%M:%S")
355         end
356
357         def normalize_cvs_path(path)
358           normalize_path(path.gsub(/Attic\//,''))
359         end
360
361         def normalize_path(path)
362           path.sub(/^(\/)*(.*)/,'\2').sub(/(.*)(,v)+/,'\1')
363         end
364
365         def path_with_proj(path)
366           "#{url}#{with_leading_slash(path)}"
367         end
368         private :path_with_proj
369
370         class Revision < Redmine::Scm::Adapters::Revision
371           # Returns the readable identifier
372           def format_identifier
373             revision.to_s
374           end
375         end
376
377         def scm_cmd(*args, &block)
378           full_args = [CVS_BIN, '-d', root_url]
379           full_args += args
380           full_args_locale = []
381           full_args.map do |e|
382             full_args_locale << scm_iconv(@path_encoding, 'UTF-8', e)
383           end
384           ret = shellout(full_args_locale.map { |e| shell_quote e.to_s }.join(' '), &block)
385           if $? && $?.exitstatus != 0
386             raise ScmCommandAborted, "cvs exited with non-zero status: #{$?.exitstatus}"
387           end
388           ret
389         end
390         private :scm_cmd
391       end
392
393       class CvsRevisionHelper
394         attr_accessor :complete_rev, :revision, :base, :branchid
395
396         def initialize(complete_rev)
397           @complete_rev = complete_rev
398           parseRevision()
399         end
400
401         def branchPoint
402           return @base
403         end
404
405         def branchVersion
406           if isBranchRevision
407             return @base+"."+@branchid
408           end
409           return @base
410         end
411
412         def isBranchRevision
413           !@branchid.nil?
414         end
415
416         def prevRev
417           unless @revision == 0
418             return buildRevision( @revision - 1 )
419           end
420           return buildRevision( @revision )
421         end
422
423         def is_in_branch_with_symbol(branch_symbol)
424           bpieces = branch_symbol.split(".")
425           branch_start = "#{bpieces[0..-3].join(".")}.#{bpieces[-1]}"
426           return ( branchVersion == branch_start )
427         end
428
429         private
430         def buildRevision(rev)
431           if rev == 0
432             if @branchid.nil?
433               @base + ".0"
434             else
435               @base
436             end
437           elsif @branchid.nil?
438             @base + "." + rev.to_s
439           else
440             @base + "." + @branchid + "." + rev.to_s
441           end
442         end
443
444         # Interpretiert die cvs revisionsnummern wie z.b. 1.14 oder 1.3.0.15
445         def parseRevision()
446           pieces = @complete_rev.split(".")
447           @revision = pieces.last.to_i
448           baseSize = 1
449           baseSize += (pieces.size / 2)
450           @base = pieces[0..-baseSize].join(".")
451           if baseSize > 2
452             @branchid = pieces[-2]
453           end
454         end
455       end
456     end
457   end
458 end