1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
|
# frozen_string_literal: true
class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationController
include ToggleSubscriptionAction
include IssuableActions
include RendersCommits
include RendersAssignees
include ToggleAwardEmoji
include IssuableCollections
include RecordUserLastActivity
include SourcegraphDecorator
include DiffHelper
include Gitlab::Cache::Helpers
include MergeRequestsHelper
prepend_before_action(only: [:index]) { authenticate_sessionless_user!(:rss) }
skip_before_action :merge_request, only: [:index, :bulk_update, :export_csv]
before_action :apply_diff_view_cookie!, only: [:show, :diffs]
before_action :disable_query_limiting, only: [:assign_related_issues, :update]
before_action :authorize_update_issuable!, only: [:close, :edit, :update, :remove_wip, :sort]
before_action :authorize_read_actual_head_pipeline!, only: [
:test_reports,
:exposed_artifacts,
:coverage_reports,
:terraform_reports,
:accessibility_reports,
:codequality_reports,
:codequality_mr_diff_reports
]
before_action :set_issuables_index, only: [:index]
before_action :check_search_rate_limit!, only: [:index], if: -> { params[:search].present? }
before_action :authenticate_user!, only: [:assign_related_issues]
before_action :check_user_can_push_to_source_branch!, only: [:rebase]
before_action only: :index do
push_frontend_feature_flag(:mr_approved_filter, type: :ops)
end
before_action only: [:show, :diffs] do
push_frontend_feature_flag(:core_security_mr_widget_counts, project)
push_frontend_feature_flag(:moved_mr_sidebar, project)
push_frontend_feature_flag(:sast_reports_in_inline_diff, project)
push_frontend_feature_flag(:mr_experience_survey, project)
push_force_frontend_feature_flag(:summarize_my_code_review, summarize_my_code_review_enabled?)
push_frontend_feature_flag(:ci_job_failures_in_mr, project)
push_frontend_feature_flag(:mr_pipelines_graphql, project)
push_frontend_feature_flag(:notifications_todos_buttons, current_user)
push_frontend_feature_flag(:widget_pipeline_pass_subscription_update, project)
push_frontend_feature_flag(:mr_request_changes, current_user)
end
before_action only: [:edit] do
if can?(current_user, :fill_in_merge_request_template, project)
push_frontend_feature_flag(:fill_in_mr_template, project)
end
end
around_action :allow_gitaly_ref_name_caching, only: [:index, :show, :diffs, :discussions]
after_action :log_merge_request_show, only: [:show, :diffs]
feature_category :code_review_workflow, [
:assign_related_issues, :bulk_update, :cancel_auto_merge,
:commit_change_content, :commits, :context_commits, :destroy,
:discussions, :edit, :index, :merge, :rebase, :remove_wip,
:show, :diffs, :toggle_award_emoji, :toggle_subscription, :update
]
feature_category :code_testing, [:test_reports, :coverage_reports]
feature_category :code_quality, [:codequality_reports, :codequality_mr_diff_reports]
feature_category :code_testing, [:accessibility_reports]
feature_category :infrastructure_as_code, [:terraform_reports]
feature_category :continuous_integration, [:pipeline_status, :pipelines, :exposed_artifacts]
urgency :high, [:export_csv]
urgency :low, [
:index,
:show,
:diffs,
:commits,
:bulk_update,
:edit,
:update,
:cancel_auto_merge,
:merge,
:ci_environments_status,
:destroy,
:rebase,
:discussions,
:pipelines,
:coverage_reports,
:test_reports,
:codequality_mr_diff_reports,
:codequality_reports,
:terraform_reports
]
urgency :low, [:pipeline_status, :pipelines, :exposed_artifacts]
def index
@merge_requests = @issuables
respond_to do |format|
format.html
format.atom { render layout: 'xml' }
end
end
def show
show_merge_request
end
def diffs
show_merge_request
end
def commits
# Get context commits from repository
@context_commits =
set_commits_for_rendering(
@merge_request.recent_context_commits
)
per_page = [
(params[:per_page] || MergeRequestDiff::COMMITS_SAFE_SIZE).to_i,
MergeRequestDiff::COMMITS_SAFE_SIZE
].min
recent_commits = @merge_request
.recent_commits(load_from_gitaly: true, limit: per_page, page: params[:page])
.with_latest_pipeline(@merge_request.source_branch)
.with_markdown_cache
@next_page = recent_commits.next_page
@commits = set_commits_for_rendering(
recent_commits,
commits_count: @merge_request.commits_count
)
commits_count = if @merge_request.preparing?
'-'
else
@merge_request.commits_count + @merge_request.context_commits_count
end
render json: {
html: view_to_html_string('projects/merge_requests/_commits'),
next_page: @next_page,
count: commits_count
}
end
def pipelines
set_pipeline_variables
@pipelines = @pipelines.page(params[:page])
Gitlab::PollingInterval.set_header(response, interval: 10_000)
render json: {
pipelines: PipelineSerializer
.new(project: @project, current_user: @current_user)
.with_pagination(request, response)
.represent(
@pipelines,
preload: true,
disable_failed_builds: true
),
count: {
all: @pipelines.count
}
}
end
def sast_reports
reports_response(merge_request.compare_sast_reports(current_user), head_pipeline)
end
def secret_detection_reports
reports_response(merge_request.compare_secret_detection_reports(current_user), head_pipeline)
end
def context_commits
# Get commits from repository
# or from cache if already merged
commits = ContextCommitsFinder.new(project, @merge_request, {
search: params[:search],
author: params[:author],
committed_before: convert_date_to_epoch(params[:committed_before]),
committed_after: convert_date_to_epoch(params[:committed_after]),
limit: params[:limit]
}).execute
render json: CommitEntity.represent(commits, { type: :full, request: merge_request })
end
def test_reports
reports_response(@merge_request.compare_test_reports)
end
def accessibility_reports
if @merge_request.has_accessibility_reports?
reports_response(@merge_request.compare_accessibility_reports)
else
head :no_content
end
end
def coverage_reports
if @merge_request.has_coverage_reports?
reports_response(@merge_request.find_coverage_reports)
else
head :no_content
end
end
# documented in doc/development/rails_endpoints/index.md
def codequality_mr_diff_reports
reports_response(@merge_request.find_codequality_mr_diff_reports, head_pipeline)
end
# documented in doc/development/rails_endpoints/index.md
def codequality_reports
reports_response(@merge_request.compare_codequality_reports)
end
def terraform_reports
reports_response(@merge_request.find_terraform_reports)
end
def exposed_artifacts
if @merge_request.has_exposed_artifacts?
reports_response(@merge_request.find_exposed_artifacts)
else
head :no_content
end
end
def edit
define_edit_vars
end
def update
@merge_request = ::MergeRequests::UpdateService
.new(project: project, current_user: current_user, params: merge_request_update_params)
.execute(@merge_request)
respond_to do |format|
format.html do
if @merge_request.errors.present?
define_edit_vars
render :edit
else
redirect_to project_merge_request_path(@merge_request.target_project, @merge_request)
end
end
format.json do
if merge_request.errors.present?
render json: @merge_request.errors, status: :bad_request
else
render json: serializer.represent(@merge_request, serializer: params[:serializer] || 'basic')
end
end
end
rescue ActiveRecord::StaleObjectError
define_edit_vars if request.format.html?
render_conflict_response
end
def remove_wip
@merge_request = ::MergeRequests::UpdateService
.new(project: project, current_user: current_user, params: { wip_event: 'ready' })
.execute(@merge_request)
render json: serialize_widget(@merge_request)
end
def commit_change_content
render partial: 'projects/merge_requests/widget/commit_change_content', layout: false
end
def cancel_auto_merge
unless @merge_request.can_cancel_auto_merge?(current_user)
return access_denied!
end
AutoMergeService.new(project, current_user).cancel(@merge_request)
render json: serialize_widget(@merge_request)
end
def merge
access_check_result = merge_access_check
return access_check_result if access_check_result
status = merge!
Gitlab::ApplicationContext.push(merge_action_status: status.to_s)
if @merge_request.merge_error
render json: { status: status, merge_error: @merge_request.merge_error }
else
render json: { status: status }
end
end
def assign_related_issues
result = ::MergeRequests::AssignIssuesService
.new(project: project, current_user: current_user, params: { merge_request: @merge_request })
.execute
case result[:count]
when 0
flash[:alert] = _("Failed to assign you issues related to the merge request.")
else
flash[:notice] = n_("An issue has been assigned to you.", "%d issues have been assigned to you.", result[:count])
end
redirect_to(merge_request_path(@merge_request))
end
def pipeline_status
render json: PipelineSerializer
.new(project: @project, current_user: @current_user)
.represent_status(head_pipeline)
end
def ci_environments_status
environments =
if ci_environments_status_on_merge_result?
EnvironmentStatus.for_deployed_merge_request(@merge_request, current_user)
else
EnvironmentStatus.for_merge_request(@merge_request, current_user)
end
render json: EnvironmentStatusSerializer.new(current_user: current_user).represent(environments)
end
def rebase
@merge_request
.rebase_async(current_user.id, skip_ci: Gitlab::Utils.to_boolean(merge_params[:skip_ci], default: false))
head :ok
rescue MergeRequest::RebaseLockTimeout => e
render json: { merge_error: e.message }, status: :conflict
end
def discussions
if Feature.enabled?(:only_highlight_discussions_requested, project)
super do |discussion_notes|
note_ids = discussion_notes.flat_map { |x| x.notes.collect(&:id) }
merge_request.discussions_diffs.load_highlight(diff_note_ids: note_ids)
end
else
merge_request.discussions_diffs.load_highlight
super
end
end
def export_csv
IssuableExportCsvWorker.perform_async(:merge_request, current_user.id, project.id, finder_options.to_h) # rubocop:disable CodeReuse/Worker
index_path = project_merge_requests_path(project)
message = _('Your CSV export has started. It will be emailed to %{email} when complete.') %
{ email: current_user.notification_email_or_default }
redirect_to(index_path, notice: message)
end
protected
alias_method :subscribable_resource, :merge_request
alias_method :issuable, :merge_request
alias_method :awardable, :merge_request
def sorting_field
MergeRequest::SORTING_PREFERENCE_FIELD
end
def merge_params
params.permit(merge_params_attributes)
end
def merge_params_attributes
MergeRequest::KNOWN_MERGE_PARAMS
end
def auto_merge_requested?
# Support params[:merge_when_pipeline_succeeds] during the transition period
params[:auto_merge_strategy].present? || params[:merge_when_pipeline_succeeds].present?
end
private
def show_merge_request
close_merge_request_if_no_source_project
@merge_request.check_mergeability(async: true)
respond_to do |format|
format.html do
# use next to appease Rubocop
next render('invalid') if target_branch_missing?
render_html_page
end
format.json do
Gitlab::PollingInterval.set_header(response, interval: 10_000)
if params[:serializer] == 'sidebar_extras'
cache_context = [
params[:serializer],
current_user&.cache_key,
@merge_request.merge_request_assignees.map(&:cache_key),
@merge_request.merge_request_reviewers.map(&:cache_key)
]
render_cached(
@merge_request,
with: serializer,
cache_context: ->(_) { [Digest::SHA256.hexdigest(cache_context.to_s)] },
serializer: params[:serializer]
)
else
render json: serializer.represent(@merge_request, serializer: params[:serializer])
end
end
format.patch do
next render_404 unless @merge_request.diff_refs
send_git_patch @project.repository, @merge_request.diff_refs
end
format.diff do
next render_404 unless @merge_request.diff_refs
send_git_diff @project.repository, @merge_request.diff_refs
end
end
end
def render_html_page
preload_assignees_for_render(@merge_request)
# Build a note object for comment form
@note = @project.notes.new(noteable: @merge_request)
@noteable = @merge_request
@commits_count = @merge_request.commits_count + @merge_request.context_commits_count
@diffs_count = get_diffs_count
@issuable_sidebar = serializer.represent(@merge_request, serializer: 'sidebar')
@current_user_data = Gitlab::Json
.dump(UserSerializer.new(project: @project)
.represent(current_user, {}, MergeRequestCurrentUserEntity))
@show_whitespace_default = current_user.nil? || current_user.show_whitespace_in_diffs
@file_by_file_default = current_user&.view_diffs_file_by_file
if @merge_request.has_coverage_reports?
@coverage_path = coverage_reports_project_merge_request_path(@project, @merge_request, format: :json)
end
@update_current_user_path = expose_path(api_v4_user_preferences_path)
@endpoint_metadata_url = endpoint_metadata_url(@project, @merge_request)
@endpoint_diff_batch_url = endpoint_diff_batch_url(@project, @merge_request)
@diffs_batch_cache_key = @merge_request.merge_head_diff&.id if merge_request.diffs_batch_cache_with_max_age?
set_pipeline_variables
@number_of_pipelines = @pipelines.size
render
end
def get_diffs_count
if show_only_context_commits?
@merge_request.context_commits_diff.raw_diffs.size
else
@merge_request.diff_size
end
end
def merge_request_update_params
merge_request_params.merge!(params.permit(:merge_request_diff_head_sha))
end
def head_pipeline
strong_memoize(:head_pipeline) do
pipeline = @merge_request.head_pipeline
pipeline if can?(current_user, :read_pipeline, pipeline)
end
end
def ci_environments_status_on_merge_result?
params[:environment_target] == 'merge_commit'
end
def target_branch_missing?
@merge_request.has_no_commits? && !@merge_request.target_branch_exists?
end
def merge!
# Disable the CI check if auto_merge_strategy is specified since we have
# to wait until CI completes to know
skipped_checks = @merge_request.skipped_mergeable_checks(
auto_merge_requested: auto_merge_requested?,
auto_merge_strategy: params[:auto_merge_strategy]
)
unless @merge_request.mergeable?(**skipped_checks)
return :failed
end
squashing = params.fetch(:squash, false)
merge_service = ::MergeRequests::MergeService
.new(project: @project, current_user: current_user, params: merge_params)
unless merge_service.hooks_validation_pass?(@merge_request, validate_squash_message: squashing)
return :hook_validation_error
end
return :sha_mismatch if params[:sha] != @merge_request.diff_head_sha
@merge_request.update(merge_error: nil, squash: squashing)
if auto_merge_requested?
if merge_request.auto_merge_enabled?
# TODO: We should have a dedicated endpoint for updating merge params.
# See https://gitlab.com/gitlab-org/gitlab-foss/issues/63130.
AutoMergeService.new(project, current_user, merge_params).update(merge_request)
else
AutoMergeService.new(project, current_user, merge_params)
.execute(
merge_request,
params[:auto_merge_strategy] || AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS
)
end
else
@merge_request.merge_async(current_user.id, merge_params)
:success
end
end
def serialize_widget(merge_request)
cached_data = serializer.represent(merge_request, serializer: 'poll_cached_widget')
widget_data = serializer.represent(merge_request, serializer: 'poll_widget')
cached_data.merge!(widget_data)
end
def serializer
@serializer ||= MergeRequestSerializer.new(current_user: current_user, project: merge_request.project)
end
def define_edit_vars
@source_project = @merge_request.source_project
@target_project = @merge_request.target_project
@noteable = @merge_request
# FIXME: We have to assign a presenter to another instance variable
# due to class_name checks being made with issuable classes
@mr_presenter = @merge_request.present(current_user: current_user)
end
def finder_type
MergeRequestsFinder
end
def check_user_can_push_to_source_branch!
result = MergeRequests::RebaseService
.new(project: @merge_request.source_project, current_user: current_user)
.validate(@merge_request)
return if result.success?
render json: { merge_error: result.message }, status: :forbidden
end
def merge_access_check
access_denied! unless @merge_request.can_be_merged_by?(current_user)
end
def disable_query_limiting
# Also see https://gitlab.com/gitlab-org/gitlab/-/issues/20827
Gitlab::QueryLimiting.disable!('https://gitlab.com/gitlab-org/gitlab/-/issues/20824')
end
def reports_response(report_comparison, pipeline = nil)
if pipeline&.active?
::Gitlab::PollingInterval.set_header(response, interval: 3000)
render json: '', status: :no_content && return
end
case report_comparison[:status]
when :parsing
::Gitlab::PollingInterval.set_header(response, interval: 3000)
render json: '', status: :no_content
when :parsed
render json: Gitlab::Json.dump(report_comparison[:data]), status: :ok
when :error
render json: { status_reason: report_comparison[:status_reason] }, status: :bad_request
else
raise "Failed to build comparison response as comparison yielded unknown status '#{report_comparison[:status]}'"
end
end
def log_merge_request_show
return unless current_user && @merge_request
::Gitlab::Search::RecentMergeRequests.new(user: current_user).log_view(@merge_request)
end
def authorize_read_actual_head_pipeline!
return render_404 unless can?(current_user, :read_build, merge_request.actual_head_pipeline)
end
def show_whitespace
current_user&.show_whitespace_in_diffs ? '0' : '1'
end
def endpoint_metadata_url(project, merge_request)
params = request.query_parameters.merge(view: 'inline', diff_head: true, w: show_whitespace)
diffs_metadata_project_json_merge_request_path(project, merge_request, 'json', params)
end
def endpoint_diff_batch_url(project, merge_request)
per_page = current_user&.view_diffs_file_by_file ? '1' : DIFF_BATCH_ENDPOINT_PER_PAGE.to_s
params = request
.query_parameters
.merge(view: 'inline', diff_head: true, w: show_whitespace, page: '0', per_page: per_page)
params[:ck] = merge_request.merge_head_diff&.id if merge_request.diffs_batch_cache_with_max_age?
diffs_batch_project_json_merge_request_path(project, merge_request, 'json', params)
end
def convert_date_to_epoch(date)
Date.strptime(date, "%Y-%m-%d")&.to_time&.to_i if date
rescue Date::Error, TypeError
end
def summarize_my_code_review_enabled?
namespace = project&.group&.root_ancestor
return false if namespace.nil?
Feature.enabled?(:summarize_my_code_review, current_user) &&
namespace.group_namespace? &&
namespace.licensed_feature_available?(:summarize_my_mr_code_review) &&
Gitlab::Llm::StageCheck.available?(namespace, :summarize_my_mr_code_review)
end
end
Projects::MergeRequestsController.prepend_mod_with('Projects::MergeRequestsController')
|