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.

repositories_controller.rb 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. require 'digest/sha1'
  19. require 'redmine/scm/adapters'
  20. class ChangesetNotFound < StandardError; end
  21. class InvalidRevisionParam < StandardError; end
  22. class RepositoriesController < ApplicationController
  23. menu_item :repository
  24. menu_item :settings, :only => [:new, :create, :edit, :update, :destroy, :committers]
  25. default_search_scope :changesets
  26. before_action :find_project_by_project_id, :only => [:new, :create]
  27. before_action :build_new_repository_from_params, :only => [:new, :create]
  28. before_action :find_repository, :only => [:edit, :update, :destroy, :committers]
  29. before_action :find_project_repository, :except => [:new, :create, :edit, :update, :destroy, :committers]
  30. before_action :find_changeset, :only => [:revision, :add_related_issue, :remove_related_issue]
  31. before_action :authorize
  32. accept_rss_auth :revisions
  33. rescue_from Redmine::Scm::Adapters::CommandFailed, :with => :show_error_command_failed
  34. def new
  35. @repository.is_default = @project.repository.nil?
  36. end
  37. def create
  38. if @repository.save
  39. redirect_to settings_project_path(@project, :tab => 'repositories')
  40. else
  41. render :action => 'new'
  42. end
  43. end
  44. def edit
  45. end
  46. def update
  47. @repository.safe_attributes = params[:repository]
  48. if @repository.save
  49. redirect_to settings_project_path(@project, :tab => 'repositories')
  50. else
  51. render :action => 'edit'
  52. end
  53. end
  54. def committers
  55. @committers = @repository.committers
  56. @users = @project.users.to_a
  57. additional_user_ids = @committers.collect(&:last).collect(&:to_i) - @users.collect(&:id)
  58. @users += User.where(:id => additional_user_ids).to_a unless additional_user_ids.empty?
  59. @users.compact!
  60. @users.sort!
  61. if request.post? && params[:committers].present?
  62. # Build a hash with repository usernames as keys and corresponding user ids as values
  63. @repository.committer_ids = params[:committers].values.inject({}) {|h, c| h[c.first] = c.last; h}
  64. flash[:notice] = l(:notice_successful_update)
  65. redirect_to settings_project_path(@project, :tab => 'repositories')
  66. end
  67. end
  68. def destroy
  69. @repository.destroy if request.delete?
  70. redirect_to settings_project_path(@project, :tab => 'repositories')
  71. end
  72. def show
  73. @repository.fetch_changesets if @project.active? && Setting.autofetch_changesets? && @path.empty?
  74. @entries = @repository.entries(@path, @rev)
  75. @changeset = @repository.find_changeset_by_name(@rev)
  76. if request.xhr?
  77. @entries ? render(:partial => 'dir_list_content') : head(200)
  78. else
  79. (show_error_not_found; return) unless @entries
  80. @changesets = @repository.latest_changesets(@path, @rev)
  81. @properties = @repository.properties(@path, @rev)
  82. @repositories = @project.repositories
  83. render :action => 'show'
  84. end
  85. end
  86. alias_method :browse, :show
  87. def changes
  88. @entry = @repository.entry(@path, @rev)
  89. (show_error_not_found; return) unless @entry
  90. @changesets = @repository.latest_changesets(@path, @rev, Setting.repository_log_display_limit.to_i)
  91. @properties = @repository.properties(@path, @rev)
  92. @changeset = @repository.find_changeset_by_name(@rev)
  93. end
  94. def revisions
  95. @changeset_count = @repository.changesets.count
  96. @changeset_pages = Paginator.new @changeset_count,
  97. per_page_option,
  98. params['page']
  99. @changesets = @repository.changesets.
  100. limit(@changeset_pages.per_page).
  101. offset(@changeset_pages.offset).
  102. includes(:user, :repository, :parents).
  103. to_a
  104. respond_to do |format|
  105. format.html { render :layout => false if request.xhr? }
  106. format.atom { render_feed(@changesets, :title => "#{@project.name}: #{l(:label_revision_plural)}") }
  107. end
  108. end
  109. def raw
  110. entry_and_raw(true)
  111. end
  112. def entry
  113. entry_and_raw(false)
  114. end
  115. def entry_and_raw(is_raw)
  116. @entry = @repository.entry(@path, @rev)
  117. (show_error_not_found; return) unless @entry
  118. # If the entry is a dir, show the browser
  119. (show; return) if @entry.is_dir?
  120. if is_raw
  121. # Force the download
  122. send_opt = { :filename => filename_for_content_disposition(@path.split('/').last) }
  123. send_type = Redmine::MimeType.of(@path)
  124. send_opt[:type] = send_type.to_s if send_type
  125. send_opt[:disposition] = disposition(@path)
  126. send_data @repository.cat(@path, @rev), send_opt
  127. else
  128. # set up pagination from entry to entry
  129. parent_path = @path.split('/')[0...-1].join('/')
  130. @entries = @repository.entries(parent_path, @rev).reject(&:is_dir?)
  131. if index = @entries.index{|e| e.name == @entry.name}
  132. @paginator = Redmine::Pagination::Paginator.new(@entries.size, 1, index+1)
  133. end
  134. if !@entry.size || @entry.size <= Setting.file_max_size_displayed.to_i.kilobyte
  135. content = @repository.cat(@path, @rev)
  136. (show_error_not_found; return) unless content
  137. if content.size <= Setting.file_max_size_displayed.to_i.kilobyte &&
  138. is_entry_text_data?(content, @path)
  139. # TODO: UTF-16
  140. # Prevent empty lines when displaying a file with Windows style eol
  141. # Is this needed? AttachmentsController simply reads file.
  142. @content = content.gsub("\r\n", "\n")
  143. end
  144. end
  145. @changeset = @repository.find_changeset_by_name(@rev)
  146. end
  147. end
  148. private :entry_and_raw
  149. def is_entry_text_data?(ent, path)
  150. # UTF-16 contains "\x00".
  151. # It is very strict that file contains less than 30% of ascii symbols
  152. # in non Western Europe.
  153. return true if Redmine::MimeType.is_type?('text', path)
  154. # Ruby 1.8.6 has a bug of integer divisions.
  155. # http://apidock.com/ruby/v1_8_6_287/String/is_binary_data%3F
  156. return false if Redmine::Scm::Adapters::ScmData.binary?(ent)
  157. true
  158. end
  159. private :is_entry_text_data?
  160. def annotate
  161. @entry = @repository.entry(@path, @rev)
  162. (show_error_not_found; return) unless @entry
  163. @annotate = @repository.scm.annotate(@path, @rev)
  164. if @annotate.nil? || @annotate.empty?
  165. @annotate = nil
  166. @error_message = l(:error_scm_annotate)
  167. else
  168. ann_buf_size = 0
  169. @annotate.lines.each do |buf|
  170. ann_buf_size += buf.size
  171. end
  172. if ann_buf_size > Setting.file_max_size_displayed.to_i.kilobyte
  173. @annotate = nil
  174. @error_message = l(:error_scm_annotate_big_text_file)
  175. end
  176. end
  177. @changeset = @repository.find_changeset_by_name(@rev)
  178. end
  179. def revision
  180. respond_to do |format|
  181. format.html
  182. format.js {render :layout => false}
  183. end
  184. end
  185. # Adds a related issue to a changeset
  186. # POST /projects/:project_id/repository/(:repository_id/)revisions/:rev/issues
  187. def add_related_issue
  188. issue_id = params[:issue_id].to_s.sub(/^#/,'')
  189. @issue = @changeset.find_referenced_issue_by_id(issue_id)
  190. if @issue && (!@issue.visible? || @changeset.issues.include?(@issue))
  191. @issue = nil
  192. end
  193. if @issue
  194. @changeset.issues << @issue
  195. end
  196. end
  197. # Removes a related issue from a changeset
  198. # DELETE /projects/:project_id/repository/(:repository_id/)revisions/:rev/issues/:issue_id
  199. def remove_related_issue
  200. @issue = Issue.visible.find_by_id(params[:issue_id])
  201. if @issue
  202. @changeset.issues.delete(@issue)
  203. end
  204. end
  205. def diff
  206. if params[:format] == 'diff'
  207. @diff = @repository.diff(@path, @rev, @rev_to)
  208. (show_error_not_found; return) unless @diff
  209. filename = +"changeset_r#{@rev}"
  210. filename << "_r#{@rev_to}" if @rev_to
  211. send_data @diff.join, :filename => "#{filename}.diff",
  212. :type => 'text/x-patch',
  213. :disposition => 'attachment'
  214. else
  215. @diff_type = params[:type] || User.current.pref[:diff_type] || 'inline'
  216. @diff_type = 'inline' unless %w(inline sbs).include?(@diff_type)
  217. # Save diff type as user preference
  218. if User.current.logged? && @diff_type != User.current.pref[:diff_type]
  219. User.current.pref[:diff_type] = @diff_type
  220. User.current.preference.save
  221. end
  222. @cache_key = "repositories/diff/#{@repository.id}/" +
  223. Digest::MD5.hexdigest("#{@path}-#{@rev}-#{@rev_to}-#{@diff_type}-#{current_language}")
  224. unless read_fragment(@cache_key)
  225. @diff = @repository.diff(@path, @rev, @rev_to)
  226. show_error_not_found unless @diff
  227. end
  228. @changeset = @repository.find_changeset_by_name(@rev)
  229. @changeset_to = @rev_to ? @repository.find_changeset_by_name(@rev_to) : nil
  230. @diff_format_revisions = @repository.diff_format_revisions(@changeset, @changeset_to)
  231. end
  232. end
  233. def stats
  234. end
  235. # Returns JSON data for repository graphs
  236. def graph
  237. data = nil
  238. case params[:graph]
  239. when "commits_per_month"
  240. data = graph_commits_per_month(@repository)
  241. when "commits_per_author"
  242. data = graph_commits_per_author(@repository)
  243. end
  244. if data
  245. render :json => data
  246. else
  247. render_404
  248. end
  249. end
  250. private
  251. def build_new_repository_from_params
  252. scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first
  253. unless @repository = Repository.factory(scm)
  254. render_404
  255. return
  256. end
  257. @repository.project = @project
  258. @repository.safe_attributes = params[:repository]
  259. @repository
  260. end
  261. def find_repository
  262. @repository = Repository.find(params[:id])
  263. @project = @repository.project
  264. rescue ActiveRecord::RecordNotFound
  265. render_404
  266. end
  267. REV_PARAM_RE = %r{\A[a-f0-9]*\Z}i
  268. def find_project_repository
  269. @project = Project.find(params[:id])
  270. if params[:repository_id].present?
  271. @repository = @project.repositories.find_by_identifier_param(params[:repository_id])
  272. else
  273. @repository = @project.repository
  274. end
  275. (render_404; return false) unless @repository
  276. @path = params[:path].is_a?(Array) ? params[:path].join('/') : params[:path].to_s
  277. @rev = params[:rev].blank? ? @repository.default_branch : params[:rev].to_s.strip
  278. @rev_to = params[:rev_to]
  279. unless REV_PARAM_RE.match?(@rev.to_s) && REV_PARAM_RE.match?(@rev_to.to_s)
  280. if @repository.branches.blank?
  281. raise InvalidRevisionParam
  282. end
  283. end
  284. rescue ActiveRecord::RecordNotFound
  285. render_404
  286. rescue InvalidRevisionParam
  287. show_error_not_found
  288. end
  289. def find_changeset
  290. if @rev.present?
  291. @changeset = @repository.find_changeset_by_name(@rev)
  292. end
  293. show_error_not_found unless @changeset
  294. end
  295. def show_error_not_found
  296. render_error :message => l(:error_scm_not_found), :status => 404
  297. end
  298. # Handler for Redmine::Scm::Adapters::CommandFailed exception
  299. def show_error_command_failed(exception)
  300. render_error l(:error_scm_command_failed, exception.message)
  301. end
  302. def graph_commits_per_month(repository)
  303. date_to = User.current.today
  304. date_from = date_to << 11
  305. date_from = Date.civil(date_from.year, date_from.month, 1)
  306. commits_by_day = Changeset.
  307. where("repository_id = ? AND commit_date BETWEEN ? AND ?", repository.id, date_from, date_to).
  308. group(:commit_date).
  309. count
  310. commits_by_month = [0] * 12
  311. commits_by_day.each {|c| commits_by_month[(date_to.month - c.first.to_date.month) % 12] += c.last }
  312. changes_by_day = Change.
  313. joins(:changeset).
  314. where("#{Changeset.table_name}.repository_id = ? AND #{Changeset.table_name}.commit_date BETWEEN ? AND ?", repository.id, date_from, date_to).
  315. group(:commit_date).
  316. count
  317. changes_by_month = [0] * 12
  318. changes_by_day.each {|c| changes_by_month[(date_to.month - c.first.to_date.month) % 12] += c.last }
  319. fields = []
  320. today = User.current.today
  321. 12.times {|m| fields << month_name(((today.month - 1 - m) % 12) + 1)}
  322. data = {
  323. :labels => fields.reverse,
  324. :commits => commits_by_month[0..11].reverse,
  325. :changes => changes_by_month[0..11].reverse
  326. }
  327. end
  328. def graph_commits_per_author(repository)
  329. #data
  330. stats = repository.stats_by_author
  331. fields, commits_data, changes_data = [], [], []
  332. stats.each do |name, hsh|
  333. fields << name
  334. commits_data << hsh[:commits_count]
  335. changes_data << hsh[:changes_count]
  336. end
  337. #expand to 10 values if needed
  338. fields = fields + [""]*(10 - fields.length) if fields.length<10
  339. commits_data = commits_data + [0]*(10 - commits_data.length) if commits_data.length<10
  340. changes_data = changes_data + [0]*(10 - changes_data.length) if changes_data.length<10
  341. # Remove email address in usernames
  342. fields = fields.collect {|c| c.gsub(%r{<.+@.+>}, '') }
  343. data = {
  344. :labels => fields.reverse,
  345. :commits => commits_data.reverse,
  346. :changes => changes_data.reverse
  347. }
  348. end
  349. def disposition(path)
  350. if Redmine::MimeType.of(@path) == "application/pdf"
  351. 'inline'
  352. else
  353. 'attachment'
  354. end
  355. end
  356. end