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.

changeset.rb 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. class Changeset < ApplicationRecord
  19. belongs_to :repository
  20. belongs_to :user
  21. has_many :filechanges, :class_name => 'Change', :dependent => :delete_all
  22. has_and_belongs_to_many :issues
  23. has_and_belongs_to_many :parents,
  24. :class_name => "Changeset",
  25. :join_table => "#{table_name_prefix}changeset_parents#{table_name_suffix}",
  26. :association_foreign_key => 'parent_id', :foreign_key => 'changeset_id'
  27. has_and_belongs_to_many :children,
  28. :class_name => "Changeset",
  29. :join_table => "#{table_name_prefix}changeset_parents#{table_name_suffix}",
  30. :association_foreign_key => 'changeset_id', :foreign_key => 'parent_id'
  31. acts_as_event(
  32. :title => proc {|o| o.title},
  33. :description => :long_comments,
  34. :datetime => :committed_on,
  35. :url =>
  36. proc do |o|
  37. {:controller => 'repositories', :action => 'revision',
  38. :id => o.repository.project,
  39. :repository_id => o.repository.identifier_param, :rev => o.identifier}
  40. end
  41. )
  42. acts_as_searchable :columns => 'comments',
  43. :preload => {:repository => :project},
  44. :project_key => "#{Repository.table_name}.project_id",
  45. :date_column => :committed_on
  46. acts_as_activity_provider :timestamp => "#{table_name}.committed_on",
  47. :author_key => :user_id,
  48. :scope => proc {preload(:user, {:repository => :project})}
  49. validates_presence_of :repository_id, :revision, :committed_on, :commit_date
  50. validates_uniqueness_of :revision, :scope => :repository_id, :case_sensitive => true
  51. validates_uniqueness_of :scmid, :scope => :repository_id, :allow_nil => true, :case_sensitive => true
  52. scope :visible, (lambda do |*args|
  53. joins(:repository => :project).
  54. where(Project.allowed_to_condition(args.shift || User.current, :view_changesets, *args))
  55. end)
  56. after_create :scan_for_issues
  57. before_create :before_create_cs
  58. def revision=(r)
  59. write_attribute :revision, (r.nil? ? nil : r.to_s)
  60. end
  61. # Returns the identifier of this changeset; depending on repository backends
  62. def identifier
  63. if repository.class.respond_to? :changeset_identifier
  64. repository.class.changeset_identifier self
  65. else
  66. revision.to_s
  67. end
  68. end
  69. def committed_on=(date)
  70. self.commit_date = date
  71. super
  72. end
  73. # Returns the readable identifier
  74. def format_identifier
  75. if repository.class.respond_to? :format_changeset_identifier
  76. repository.class.format_changeset_identifier self
  77. else
  78. identifier
  79. end
  80. end
  81. def project
  82. repository.project
  83. end
  84. def author
  85. user || committer.to_s.split('<').first
  86. end
  87. def before_create_cs
  88. self.committer = self.class.to_utf8(self.committer, repository.repo_log_encoding)
  89. self.comments =
  90. self.class.normalize_comments(self.comments, repository.repo_log_encoding)
  91. self.user = repository.find_committer_user(self.committer)
  92. end
  93. def scan_for_issues
  94. scan_comment_for_issue_ids
  95. end
  96. TIMELOG_RE = /
  97. (
  98. ((\d+)(h|hours?))((\d+)(m|min)?)?
  99. |
  100. ((\d+)(h|hours?|m|min))
  101. |
  102. (\d+):(\d+)
  103. |
  104. (\d+([\.,]\d+)?)h?
  105. )
  106. /x
  107. def scan_comment_for_issue_ids
  108. return if comments.blank?
  109. # keywords used to reference issues
  110. ref_keywords = Setting.commit_ref_keywords.downcase.split(",").collect(&:strip)
  111. ref_keywords_any = ref_keywords.delete('*')
  112. # keywords used to fix issues
  113. fix_keywords = Setting.commit_update_keywords_array.pluck('keywords').flatten.compact
  114. kw_regexp = (ref_keywords + fix_keywords).collect{|kw| Regexp.escape(kw)}.join("|")
  115. referenced_issues = []
  116. regexp =
  117. %r{
  118. ([\s\(\[,-]|^)((#{kw_regexp})[\s:]+)?
  119. (\#\d+(\s+@#{TIMELOG_RE})?([\s,;&]+\#\d+(\s+@#{TIMELOG_RE})?)*)
  120. (?=[[:punct:]]|\s|<|$)
  121. }xi
  122. comments.scan(regexp) do |match|
  123. action = match[2].to_s.downcase
  124. refs = match[3]
  125. next unless action.present? || ref_keywords_any
  126. refs.scan(/#(\d+)(\s+@#{TIMELOG_RE})?/o).each do |m|
  127. issue = find_referenced_issue_by_id(m[0].to_i)
  128. hours = m[2]
  129. if issue && !issue_linked_to_same_commit?(issue)
  130. referenced_issues << issue
  131. # Don't update issues or log time when importing old commits
  132. unless repository.created_on && committed_on && committed_on < repository.created_on
  133. fix_issue(issue, action) if fix_keywords.include?(action)
  134. log_time(issue, hours) if hours && Setting.commit_logtime_enabled?
  135. end
  136. end
  137. end
  138. end
  139. referenced_issues.uniq!
  140. self.issues = referenced_issues unless referenced_issues.empty?
  141. end
  142. def short_comments
  143. @short_comments || split_comments.first
  144. end
  145. def long_comments
  146. @long_comments || split_comments.last
  147. end
  148. def text_tag(ref_project=nil)
  149. repo = ""
  150. if repository && repository.identifier.present?
  151. repo = "#{repository.identifier}|"
  152. end
  153. tag = scmid? ? "commit:#{repo}#{scmid}" : "#{repo}r#{revision}"
  154. if ref_project && project && ref_project != project
  155. tag = "#{project.identifier}:#{tag}"
  156. end
  157. tag
  158. end
  159. # Returns the title used for the changeset in the activity/search results
  160. def title
  161. repo = (repository && repository.identifier.present?) ? " (#{repository.identifier})" : ''
  162. comm = short_comments.blank? ? '' : (': ' + short_comments)
  163. "#{l(:label_revision)} #{format_identifier}#{repo}#{comm}"
  164. end
  165. # Returns the previous changeset
  166. def previous
  167. @previous ||= Changeset.where(["id < ? AND repository_id = ?", id, repository_id]).order('id DESC').first
  168. end
  169. # Returns the next changeset
  170. def next
  171. @next ||= Changeset.where(["id > ? AND repository_id = ?", id, repository_id]).order('id ASC').first
  172. end
  173. # Creates a new Change from it's common parameters
  174. def create_change(change)
  175. Change.create(:changeset => self,
  176. :action => change[:action],
  177. :path => change[:path],
  178. :from_path => change[:from_path],
  179. :from_revision => change[:from_revision])
  180. end
  181. # Finds an issue that can be referenced by the commit message
  182. def find_referenced_issue_by_id(id)
  183. return nil if id.blank?
  184. issue = Issue.find_by_id(id.to_i)
  185. if Setting.commit_cross_project_ref?
  186. # all issues can be referenced/fixed
  187. elsif issue
  188. # issue that belong to the repository project, a subproject or a parent project only
  189. unless issue.project &&
  190. (project == issue.project || project.is_ancestor_of?(issue.project) ||
  191. project.is_descendant_of?(issue.project))
  192. issue = nil
  193. end
  194. end
  195. issue
  196. end
  197. private
  198. # Returns true if the issue is already linked to the same commit
  199. # from a different repository
  200. def issue_linked_to_same_commit?(issue)
  201. repository.same_commits_in_scope(issue.changesets, self).any?
  202. end
  203. # Updates the +issue+ according to +action+
  204. def fix_issue(issue, action)
  205. # the issue may have been updated by the closure of another one (eg. duplicate)
  206. issue.reload
  207. # don't change the status is the issue is closed
  208. return if issue.closed?
  209. journal = issue.init_journal(user || User.anonymous,
  210. ll(Setting.default_language,
  211. :text_status_changed_by_changeset,
  212. text_tag(issue.project)))
  213. rule = Setting.commit_update_keywords_array.detect do |rule|
  214. rule['keywords'].include?(action) &&
  215. (rule['if_tracker_id'].blank? || rule['if_tracker_id'] == issue.tracker_id.to_s)
  216. end
  217. if rule
  218. issue.assign_attributes rule.slice(*Issue.attribute_names)
  219. end
  220. Redmine::Hook.call_hook(:model_changeset_scan_commit_for_issue_ids_pre_issue_update,
  221. {:changeset => self, :issue => issue, :action => action})
  222. if issue.changes.any?
  223. unless issue.save
  224. logger.warn("Issue ##{issue.id} could not be saved by changeset #{id}: #{issue.errors.full_messages}") if logger
  225. end
  226. else
  227. issue.clear_journal
  228. end
  229. issue
  230. end
  231. def log_time(issue, hours)
  232. time_entry =
  233. TimeEntry.new(
  234. :user => user,
  235. :hours => hours,
  236. :issue => issue,
  237. :spent_on => commit_date,
  238. :comments => l(:text_time_logged_by_changeset, :value => text_tag(issue.project),
  239. :locale => Setting.default_language)
  240. )
  241. if activity = issue.project.commit_logtime_activity
  242. time_entry.activity = activity
  243. end
  244. unless time_entry.save
  245. logger.warn("TimeEntry could not be created by changeset #{id}: #{time_entry.errors.full_messages}") if logger
  246. end
  247. time_entry
  248. end
  249. def split_comments
  250. comments =~ /\A(.+?)\r?\n(.*)$/m
  251. @short_comments = $1 || comments
  252. @long_comments = $2.to_s.strip
  253. [@short_comments, @long_comments]
  254. end
  255. # Singleton class method is public
  256. class << self
  257. # Strips and reencodes a commit log before insertion into the database
  258. def normalize_comments(str, encoding)
  259. Changeset.to_utf8(str.to_s, encoding).strip
  260. end
  261. def to_utf8(str, encoding)
  262. Redmine::CodesetUtil.to_utf8(str, encoding)
  263. end
  264. end
  265. end