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 10.0KB

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