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

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