You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cvs_adapter.rb 16KB

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