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.

abstract_adapter.rb 12KB

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