PageRenderTime 44ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/redmine/scm/adapters/abstract_adapter.rb

https://bitbucket.org/eimajenthat/redmine
Ruby | 429 lines | 392 code | 12 blank | 25 comment | 8 complexity | c505a946df41fb51748c079dfd39af3d MD5 | raw file
Possible License(s): GPL-2.0
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2013 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. require 'cgi'
  18. if RUBY_VERSION < '1.9'
  19. require 'iconv'
  20. end
  21. module Redmine
  22. module Scm
  23. module Adapters
  24. class CommandFailed < StandardError #:nodoc:
  25. end
  26. class AbstractAdapter #:nodoc:
  27. # raised if scm command exited with error, e.g. unknown revision.
  28. class ScmCommandAborted < CommandFailed; end
  29. class << self
  30. def client_command
  31. ""
  32. end
  33. def shell_quote_command
  34. if Redmine::Platform.mswin? && RUBY_PLATFORM == 'java'
  35. client_command
  36. else
  37. shell_quote(client_command)
  38. end
  39. end
  40. # Returns the version of the scm client
  41. # Eg: [1, 5, 0] or [] if unknown
  42. def client_version
  43. []
  44. end
  45. # Returns the version string of the scm client
  46. # Eg: '1.5.0' or 'Unknown version' if unknown
  47. def client_version_string
  48. v = client_version || 'Unknown version'
  49. v.is_a?(Array) ? v.join('.') : v.to_s
  50. end
  51. # Returns true if the current client version is above
  52. # or equals the given one
  53. # If option is :unknown is set to true, it will return
  54. # true if the client version is unknown
  55. def client_version_above?(v, options={})
  56. ((client_version <=> v) >= 0) || (client_version.empty? && options[:unknown])
  57. end
  58. def client_available
  59. true
  60. end
  61. def shell_quote(str)
  62. if Redmine::Platform.mswin?
  63. '"' + str.gsub(/"/, '\\"') + '"'
  64. else
  65. "'" + str.gsub(/'/, "'\"'\"'") + "'"
  66. end
  67. end
  68. end
  69. def initialize(url, root_url=nil, login=nil, password=nil,
  70. path_encoding=nil)
  71. @url = url
  72. @login = login if login && !login.empty?
  73. @password = (password || "") if @login
  74. @root_url = root_url.blank? ? retrieve_root_url : root_url
  75. end
  76. def adapter_name
  77. 'Abstract'
  78. end
  79. def supports_cat?
  80. true
  81. end
  82. def supports_annotate?
  83. respond_to?('annotate')
  84. end
  85. def root_url
  86. @root_url
  87. end
  88. def url
  89. @url
  90. end
  91. def path_encoding
  92. nil
  93. end
  94. # get info about the svn repository
  95. def info
  96. return nil
  97. end
  98. # Returns the entry identified by path and revision identifier
  99. # or nil if entry doesn't exist in the repository
  100. def entry(path=nil, identifier=nil)
  101. parts = path.to_s.split(%r{[\/\\]}).select {|n| !n.blank?}
  102. search_path = parts[0..-2].join('/')
  103. search_name = parts[-1]
  104. if search_path.blank? && search_name.blank?
  105. # Root entry
  106. Entry.new(:path => '', :kind => 'dir')
  107. else
  108. # Search for the entry in the parent directory
  109. es = entries(search_path, identifier)
  110. es ? es.detect {|e| e.name == search_name} : nil
  111. end
  112. end
  113. # Returns an Entries collection
  114. # or nil if the given path doesn't exist in the repository
  115. def entries(path=nil, identifier=nil, options={})
  116. return nil
  117. end
  118. def branches
  119. return nil
  120. end
  121. def tags
  122. return nil
  123. end
  124. def default_branch
  125. return nil
  126. end
  127. def properties(path, identifier=nil)
  128. return nil
  129. end
  130. def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={})
  131. return nil
  132. end
  133. def diff(path, identifier_from, identifier_to=nil)
  134. return nil
  135. end
  136. def cat(path, identifier=nil)
  137. return nil
  138. end
  139. def with_leading_slash(path)
  140. path ||= ''
  141. (path[0,1]!="/") ? "/#{path}" : path
  142. end
  143. def with_trailling_slash(path)
  144. path ||= ''
  145. (path[-1,1] == "/") ? path : "#{path}/"
  146. end
  147. def without_leading_slash(path)
  148. path ||= ''
  149. path.gsub(%r{^/+}, '')
  150. end
  151. def without_trailling_slash(path)
  152. path ||= ''
  153. (path[-1,1] == "/") ? path[0..-2] : path
  154. end
  155. def shell_quote(str)
  156. self.class.shell_quote(str)
  157. end
  158. private
  159. def retrieve_root_url
  160. info = self.info
  161. info ? info.root_url : nil
  162. end
  163. def target(path, sq=true)
  164. path ||= ''
  165. base = path.match(/^\//) ? root_url : url
  166. str = "#{base}/#{path}".gsub(/[?<>\*]/, '')
  167. if sq
  168. str = shell_quote(str)
  169. end
  170. str
  171. end
  172. def logger
  173. self.class.logger
  174. end
  175. def shellout(cmd, options = {}, &block)
  176. self.class.shellout(cmd, options, &block)
  177. end
  178. def self.logger
  179. Rails.logger
  180. end
  181. # Path to the file where scm stderr output is logged
  182. def self.stderr_log_file
  183. @stderr_log_path ||=
  184. Redmine::Configuration['scm_stderr_log_file'].presence ||
  185. Rails.root.join("log/#{Rails.env}.scm.stderr.log").to_s
  186. end
  187. def self.shellout(cmd, options = {}, &block)
  188. if logger && logger.debug?
  189. logger.debug "Shelling out: #{strip_credential(cmd)}"
  190. end
  191. # Capture stderr in a log file
  192. cmd = "#{cmd} 2>>#{shell_quote(stderr_log_file)}"
  193. begin
  194. mode = "r+"
  195. IO.popen(cmd, mode) do |io|
  196. io.set_encoding("ASCII-8BIT") if io.respond_to?(:set_encoding)
  197. io.close_write unless options[:write_stdin]
  198. block.call(io) if block_given?
  199. end
  200. ## If scm command does not exist,
  201. ## Linux JRuby 1.6.2 (ruby-1.8.7-p330) raises java.io.IOException
  202. ## in production environment.
  203. # rescue Errno::ENOENT => e
  204. rescue Exception => e
  205. msg = strip_credential(e.message)
  206. # The command failed, log it and re-raise
  207. logmsg = "SCM command failed, "
  208. logmsg += "make sure that your SCM command (e.g. svn) is "
  209. logmsg += "in PATH (#{ENV['PATH']})\n"
  210. logmsg += "You can configure your scm commands in config/configuration.yml.\n"
  211. logmsg += "#{strip_credential(cmd)}\n"
  212. logmsg += "with: #{msg}"
  213. logger.error(logmsg)
  214. raise CommandFailed.new(msg)
  215. end
  216. end
  217. # Hides username/password in a given command
  218. def self.strip_credential(cmd)
  219. q = (Redmine::Platform.mswin? ? '"' : "'")
  220. cmd.to_s.gsub(/(\-\-(password|username))\s+(#{q}[^#{q}]+#{q}|[^#{q}]\S+)/, '\\1 xxxx')
  221. end
  222. def strip_credential(cmd)
  223. self.class.strip_credential(cmd)
  224. end
  225. def scm_iconv(to, from, str)
  226. return nil if str.nil?
  227. return str if to == from
  228. if str.respond_to?(:force_encoding)
  229. str.force_encoding(from)
  230. begin
  231. str.encode(to)
  232. rescue Exception => err
  233. logger.error("failed to convert from #{from} to #{to}. #{err}")
  234. nil
  235. end
  236. else
  237. begin
  238. Iconv.conv(to, from, str)
  239. rescue Iconv::Failure => err
  240. logger.error("failed to convert from #{from} to #{to}. #{err}")
  241. nil
  242. end
  243. end
  244. end
  245. def parse_xml(xml)
  246. if RUBY_PLATFORM == 'java'
  247. xml = xml.sub(%r{<\?xml[^>]*\?>}, '')
  248. end
  249. ActiveSupport::XmlMini.parse(xml)
  250. end
  251. end
  252. class Entries < Array
  253. def sort_by_name
  254. dup.sort! {|x,y|
  255. if x.kind == y.kind
  256. x.name.to_s <=> y.name.to_s
  257. else
  258. x.kind <=> y.kind
  259. end
  260. }
  261. end
  262. def revisions
  263. revisions ||= Revisions.new(collect{|entry| entry.lastrev}.compact)
  264. end
  265. end
  266. class Info
  267. attr_accessor :root_url, :lastrev
  268. def initialize(attributes={})
  269. self.root_url = attributes[:root_url] if attributes[:root_url]
  270. self.lastrev = attributes[:lastrev]
  271. end
  272. end
  273. class Entry
  274. attr_accessor :name, :path, :kind, :size, :lastrev, :changeset
  275. def initialize(attributes={})
  276. self.name = attributes[:name] if attributes[:name]
  277. self.path = attributes[:path] if attributes[:path]
  278. self.kind = attributes[:kind] if attributes[:kind]
  279. self.size = attributes[:size].to_i if attributes[:size]
  280. self.lastrev = attributes[:lastrev]
  281. end
  282. def is_file?
  283. 'file' == self.kind
  284. end
  285. def is_dir?
  286. 'dir' == self.kind
  287. end
  288. def is_text?
  289. Redmine::MimeType.is_type?('text', name)
  290. end
  291. def author
  292. if changeset
  293. changeset.author.to_s
  294. elsif lastrev
  295. Redmine::CodesetUtil.replace_invalid_utf8(lastrev.author.to_s.split('<').first)
  296. end
  297. end
  298. end
  299. class Revisions < Array
  300. def latest
  301. sort {|x,y|
  302. unless x.time.nil? or y.time.nil?
  303. x.time <=> y.time
  304. else
  305. 0
  306. end
  307. }.last
  308. end
  309. end
  310. class Revision
  311. attr_accessor :scmid, :name, :author, :time, :message,
  312. :paths, :revision, :branch, :identifier,
  313. :parents
  314. def initialize(attributes={})
  315. self.identifier = attributes[:identifier]
  316. self.scmid = attributes[:scmid]
  317. self.name = attributes[:name] || self.identifier
  318. self.author = attributes[:author]
  319. self.time = attributes[:time]
  320. self.message = attributes[:message] || ""
  321. self.paths = attributes[:paths]
  322. self.revision = attributes[:revision]
  323. self.branch = attributes[:branch]
  324. self.parents = attributes[:parents]
  325. end
  326. # Returns the readable identifier.
  327. def format_identifier
  328. self.identifier.to_s
  329. end
  330. def ==(other)
  331. if other.nil?
  332. false
  333. elsif scmid.present?
  334. scmid == other.scmid
  335. elsif identifier.present?
  336. identifier == other.identifier
  337. elsif revision.present?
  338. revision == other.revision
  339. end
  340. end
  341. end
  342. class Annotate
  343. attr_reader :lines, :revisions
  344. def initialize
  345. @lines = []
  346. @revisions = []
  347. end
  348. def add_line(line, revision)
  349. @lines << line
  350. @revisions << revision
  351. end
  352. def content
  353. content = lines.join("\n")
  354. end
  355. def empty?
  356. lines.empty?
  357. end
  358. end
  359. class Branch < String
  360. attr_accessor :revision, :scmid
  361. end
  362. end
  363. end
  364. end