Read about our upcoming Code of Conduct on this issue

merge_requests_controller.rb 15.9 KB
Newer Older
1
class Projects::MergeRequestsController < Projects::ApplicationController
2
  include ToggleSubscriptionAction
Sean McGivern's avatar
Sean McGivern committed
3
  include DiffForPath
4
  include DiffHelper
5
  include IssuableActions
6
  include NotesHelper
7
  include ToggleAwardEmoji
8
  include IssuableCollections
9

10
  before_action :module_enabled
11
  before_action :merge_request, only: [
Douwe Maan's avatar
Douwe Maan committed
12
    :edit, :update, :show, :diffs, :commits, :conflicts, :builds, :pipelines, :merge, :merge_check,
Sean McGivern's avatar
Sean McGivern committed
13
    :ci_status, :toggle_subscription, :cancel_merge_when_build_succeeds, :remove_wip, :resolve_conflicts
14
  ]
15
  before_action :validates_merge_request, only: [:show, :diffs, :commits, :builds, :pipelines]
Douwe Maan's avatar
Douwe Maan committed
16
  before_action :define_show_vars, only: [:show, :diffs, :commits, :conflicts, :builds, :pipelines]
17
  before_action :define_widget_vars, only: [:merge, :cancel_merge_when_build_succeeds, :merge_check]
18
19
  before_action :define_commit_vars, only: [:diffs]
  before_action :define_diff_comment_vars, only: [:diffs]
Douwe Maan's avatar
Douwe Maan committed
20
  before_action :ensure_ref_fetched, only: [:show, :diffs, :commits, :builds, :conflicts, :pipelines]
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
21
22

  # Allow read any merge_request
23
  before_action :authorize_read_merge_request!
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
24
25

  # Allow write(create) merge_request
26
  before_action :authorize_create_merge_request!, only: [:new, :create]
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
27
28

  # Allow modify merge_request
29
  before_action :authorize_update_merge_request!, only: [:close, :edit, :update, :remove_wip, :sort]
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
30

31
32
  before_action :authorize_can_resolve_conflicts!, only: [:conflicts, :resolve_conflicts]

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
33
  def index
34
    terms = params['issue_search']
35
    @merge_requests = merge_requests_collection
36
37
38
39
40
41
42
43

    if terms.present?
      if terms =~ /\A[#!](\d+)\z/
        @merge_requests = @merge_requests.where(iid: $1)
      else
        @merge_requests = @merge_requests.full_search(terms)
      end
    end
44

45
    @merge_requests = @merge_requests.page(params[:page])
46
    @merge_requests = @merge_requests.preload(:target_project)
47

48
    @labels = @project.labels.where(title: params[:label_name])
Tap's avatar
Tap committed
49

50
51
52
53
    respond_to do |format|
      format.html
      format.json do
        render json: {
54
          html: view_to_html_string("projects/merge_requests/_merge_requests"),
Phil Hughes's avatar
Phil Hughes committed
55
          labels: @labels.as_json(methods: :text_color)
56
57
58
        }
      end
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
59
60
61
  end

  def show
62
    respond_to do |format|
63
      format.html { define_discussion_vars }
64

Douwe Maan's avatar
Douwe Maan committed
65
66
67
68
      format.json do
        render json: @merge_request
      end

69
      format.patch  do
Douwe Maan's avatar
Douwe Maan committed
70
71
72
        return render_404 unless @merge_request.diff_refs

        send_git_patch @project.repository, @merge_request.diff_refs
73
      end
Douwe Maan's avatar
Douwe Maan committed
74

75
      format.diff do
Douwe Maan's avatar
Douwe Maan committed
76
        return render_404 unless @merge_request.diff_refs
77

Douwe Maan's avatar
Douwe Maan committed
78
        send_git_diff @project.repository, @merge_request.diff_refs
79
      end
80
    end
randx's avatar
randx committed
81
82
  end

83
  def diffs
84
85
    apply_diff_view_cookie!

86
87
88
89
90
91
    @merge_request_diff =
      if params[:diff_id]
        @merge_request.merge_request_diffs.find(params[:diff_id])
      else
        @merge_request.merge_request_diff
      end
92

93
    respond_to do |format|
94
      format.html { define_discussion_vars }
95
      format.json do
96
        unless @merge_request_diff.latest?
97
98
99
100
          # Disable comments if browsing older version of the diff
          @diff_notes_disabled = true
        end

101
        @diffs = @merge_request_diff.diffs(diff_options)
102
103
104

        render json: { html: view_to_html_string("projects/merge_requests/show/_diffs") }
      end
105
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
106
107
  end

108
109
110
111
112
113
114
115
116
117
  # With an ID param, loads the MR at that ID. Otherwise, accepts the same params as #new
  # and uses that (unsaved) MR.
  #
  def diff_for_path
    if params[:id]
      merge_request
      define_diff_comment_vars
    else
      build_merge_request
      @diff_notes_disabled = true
118
      @grouped_diff_discussions = {}
119
120
121
122
    end

    define_commit_vars

123
    render_diff_for_path(@merge_request.diffs(diff_options))
124
125
  end

126
  def commits
127
    respond_to do |format|
128
129
130
131
132
      format.html do
        define_discussion_vars

        render 'show'
      end
133
134
135
136
137
138
139
140
141
      format.json do
        # Get commits from repository
        # or from cache if already merged
        @commits = @merge_request.commits
        @note_counts = Note.where(commit_id: @commits.map(&:id)).
          group(:commit_id).count

        render json: { html: view_to_html_string('projects/merge_requests/show/_commits') }
      end
142
    end
143
144
  end

145
146
  def conflicts
    respond_to do |format|
147
      format.html { define_discussion_vars }
Sean McGivern's avatar
Sean McGivern committed
148

149
      format.json do
150
        if @merge_request.conflicts_can_be_resolved_in_ui?
151
          render json: @merge_request.conflicts
152
153
154
155
156
        elsif @merge_request.can_be_merged?
          render json: {
            message: 'The merge conflicts for this merge request have already been resolved. Please return to the merge request.',
            type: 'error'
          }
157
        else
158
          render json: {
159
            message: 'The merge conflicts for this merge request cannot be resolved through GitLab. Please try to resolve them locally.',
160
161
            type: 'error'
          }
162
163
        end
      end
164
165
166
    end
  end

167
  def resolve_conflicts
168
169
170
171
172
173
174
    return render_404 unless @merge_request.conflicts_can_be_resolved_in_ui?

    if @merge_request.can_be_merged?
      render status: :bad_request, json: { message: 'The merge conflicts for this merge request have already been resolved.' }
      return
    end

175
    begin
176
      MergeRequests::ResolveService.new(@merge_request.source_project, current_user, params).execute(@merge_request)
177

178
      flash[:notice] = 'All merge conflicts were resolved. The merge request can now be merged.'
179

180
      render json: { redirect_to: namespace_project_merge_request_url(@project.namespace, @project, @merge_request, resolved_conflicts: true) }
181
182
183
    rescue Gitlab::Conflict::File::MissingResolution => e
      render status: :bad_request, json: { message: e.message }
    end
184
185
  end

Douwe Maan's avatar
Douwe Maan committed
186
187
  def builds
    respond_to do |format|
188
189
190
191
192
      format.html do
        define_discussion_vars

        render 'show'
      end
Douwe Maan's avatar
Douwe Maan committed
193
194
195
196
      format.json { render json: { html: view_to_html_string('projects/merge_requests/show/_builds') } }
    end
  end

197
  def pipelines
198
    @pipelines = @merge_request.all_pipelines
199

200
201
202
203
204
205
206
207
208
209
    respond_to do |format|
      format.html do
        define_discussion_vars

        render 'show'
      end
      format.json { render json: { html: view_to_html_string('projects/merge_requests/show/_pipelines') } }
    end
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
210
  def new
211
212
    apply_diff_view_cookie!

213
    build_merge_request
214
    @noteable = @merge_request
215
216
217
218
219
220
221
222
223

    @target_branches = if @merge_request.target_project
                         @merge_request.target_project.repository.branch_names
                       else
                         []
                       end

    @target_project = merge_request.target_project
    @source_project = merge_request.source_project
Douwe Maan's avatar
Douwe Maan committed
224
    @commits = @merge_request.compare_commits.reverse
225
    @commit = @merge_request.diff_head_commit
226
    @base_commit = @merge_request.diff_base_commit
227
    @diffs = @merge_request.diffs(diff_options) if @merge_request.compare
228
    @diff_notes_disabled = true
229
    @pipeline = @merge_request.pipeline
230
    @statuses = @pipeline.statuses.relevant if @pipeline
Douwe Maan's avatar
Douwe Maan committed
231

232
233
    @note_counts = Note.where(commit_id: @commits.map(&:id)).
      group(:commit_id).count
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
234
235
236
  end

  def create
237
    @target_branches ||= []
238
    @merge_request = MergeRequests::CreateService.new(project, current_user, merge_request_params).execute
239
240

    if @merge_request.valid?
241
      redirect_to(merge_request_path(@merge_request))
242
    else
Izaak Alpert's avatar
Izaak Alpert committed
243
244
245
      @source_project = @merge_request.source_project
      @target_project = @merge_request.target_project
      render action: "new"
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
246
247
248
    end
  end

Douwe Maan's avatar
Douwe Maan committed
249
250
251
252
253
254
  def edit
    @source_project = @merge_request.source_project
    @target_project = @merge_request.target_project
    @target_branches = @merge_request.target_project.repository.branch_names
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
255
  def update
256
    @merge_request = MergeRequests::UpdateService.new(project, current_user, merge_request_params).execute(@merge_request)
257

258
    if @merge_request.valid?
259
260
      respond_to do |format|
        format.html do
Vinnie Okada's avatar
Vinnie Okada committed
261
          redirect_to([@merge_request.target_project.namespace.becomes(Namespace),
262
                       @merge_request.target_project, @merge_request])
263
        end
264
        format.json do
265
          render json: @merge_request.to_json(include: { milestone: {}, assignee: { methods: :avatar_url }, labels: { methods: :text_color } })
266
        end
267
      end
268
    else
269
      render "edit"
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
270
    end
271
272
273
  rescue ActiveRecord::StaleObjectError
    @conflict = true
    render :edit
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
274
275
  end

276
277
278
279
280
281
282
  def remove_wip
    MergeRequests::UpdateService.new(project, current_user, title: @merge_request.wipless_title).execute(@merge_request)

    redirect_to namespace_project_merge_request_path(@project.namespace, @project, @merge_request),
      notice: "The merge request can now be merged."
  end

283
  def merge_check
284
    @merge_request.check_if_can_be_merged
285

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
286
    render partial: "projects/merge_requests/widget/show.html.haml", layout: false
Valery Sizov's avatar
Valery Sizov committed
287
288
  end

289
  def cancel_merge_when_build_succeeds
290
    return access_denied! unless @merge_request.can_cancel_merge_when_build_succeeds?(current_user)
291

292
    MergeRequests::MergeWhenBuildSucceedsService.new(@project, current_user).cancel(@merge_request)
293
294
  end

295
  def merge
296
    return access_denied! unless @merge_request.can_be_merged_by?(current_user)
297

298
299
300
    # Disable the CI check if merge_when_build_succeeds is enabled since we have
    # to wait until CI completes to know
    unless @merge_request.mergeable?(skip_ci_check: merge_when_build_succeeds_active?)
301
302
303
304
      @status = :failed
      return
    end

305
    if params[:sha] != @merge_request.diff_head_sha
306
307
308
309
      @status = :sha_mismatch
      return
    end

310
    TodoService.new.merge_merge_request(merge_request, current_user)
311

312
313
    @merge_request.update(merge_error: nil)

314
315
316
317
318
319
320
    if params[:merge_when_build_succeeds].present?
      unless @merge_request.pipeline
        @status = :failed
        return
      end

      if @merge_request.pipeline.active?
321
322
323
        MergeRequests::MergeWhenBuildSucceedsService.new(@project, current_user, merge_params)
                                                        .execute(@merge_request)
        @status = :merge_when_build_succeeds
Z.J. van de Weg's avatar
Z.J. van de Weg committed
324
325
326
      elsif @merge_request.pipeline.success?
        # This can be triggered when a user clicks the auto merge button while
        # the tests finish at about the same time
327
328
329
330
331
        MergeWorker.perform_async(@merge_request.id, current_user.id, params)
        @status = :success
      else
        @status = :failed
      end
332
    else
333
334
      MergeWorker.perform_async(@merge_request.id, current_user.id, params)
      @status = :success
335
    end
randx's avatar
randx committed
336
337
  end

338
  def branch_from
Felipe Artur's avatar
Felipe Artur committed
339
    # This is always source
Izaak Alpert's avatar
Izaak Alpert committed
340
    @source_project = @merge_request.nil? ? @project : @merge_request.source_project
341
    @commit = @repository.commit(params[:ref]) if params[:ref].present?
Phil Hughes's avatar
Phil Hughes committed
342
    render layout: false
343
344
345
  end

  def branch_to
346
    @target_project = selected_target_project
347
    @commit = @target_project.commit(params[:ref]) if params[:ref].present?
Phil Hughes's avatar
Phil Hughes committed
348
    render layout: false
349
350
  end

351
352
  def update_branches
    @target_project = selected_target_project
Izaak Alpert's avatar
Izaak Alpert committed
353
    @target_branches = @target_project.repository.branch_names
354

Phil Hughes's avatar
Phil Hughes committed
355
    render layout: false
356
357
  end

358
  def ci_status
359
360
361
362
    pipeline = @merge_request.pipeline
    if pipeline
      status = pipeline.status
      coverage = pipeline.try(:coverage)
363

Connor Shea's avatar
Connor Shea committed
364
      status = "success_with_warnings" if pipeline.success? && pipeline.has_warnings?
365

366
      status ||= "preparing"
367
368
    else
      ci_service = @merge_request.source_project.ci_service
369
      status = ci_service.commit_status(merge_request.diff_head_sha, merge_request.source_branch) if ci_service
370

371
      if ci_service.respond_to?(:commit_coverage)
372
        coverage = ci_service.commit_coverage(merge_request.diff_head_sha, merge_request.source_branch)
373
      end
374
375
376
    end

    response = {
377
      title: merge_request.title,
378
      sha: merge_request.diff_head_commit.short_id,
379
380
381
      status: status,
      coverage: coverage
    }
382
383
384
385

    render json: response
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
386
387
  protected

388
  def selected_target_project
389
390
391
392
393
    if @project.id.to_s == params[:target_project_id] || @project.forked_project_link.nil?
      @project
    else
      @project.forked_project_link.forked_from_project
    end
394
395
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
396
  def merge_request
397
    @issuable = @merge_request ||= @project.merge_requests.find_by!(iid: params[:id])
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
398
  end
399
  alias_method :subscribable_resource, :merge_request
400
  alias_method :issuable, :merge_request
401
  alias_method :awardable, :merge_request
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
402

403
  def authorize_update_merge_request!
404
    return render_404 unless can?(current_user, :update_merge_request, @merge_request)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
405
406
407
  end

  def authorize_admin_merge_request!
408
    return render_404 unless can?(current_user, :admin_merge_request, @merge_request)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
409
  end
410

411
412
413
414
  def authorize_can_resolve_conflicts!
    return render_404 unless @merge_request.conflicts_can_be_resolved_by?(current_user)
  end

415
  def module_enabled
Felipe Artur's avatar
Felipe Artur committed
416
    return render_404 unless @project.feature_available?(:merge_requests, current_user)
417
  end
418
419

  def validates_merge_request
420
421
422
    # If source project was removed (Ex. mr from fork to origin)
    return invalid_mr unless @merge_request.source_project

423
424
425
    # Show git not found page
    # if there is no saved commits between source & target branch
    if @merge_request.commits.blank?
426
427
      # and if target branch doesn't exist
      return invalid_mr unless @merge_request.target_branch_exists?
428

429
430
      # or if source branch doesn't exist
      return invalid_mr unless @merge_request.source_branch_exists?
431
    end
432
433
434
  end

  def define_show_vars
435
436
437
438
    @noteable = @merge_request
    @commits_count = @merge_request.commits.count

    @pipeline = @merge_request.pipeline
439
    @statuses = @pipeline.statuses.relevant if @pipeline
440
441
442
443
444
445
446

    if @merge_request.locked_long_ago?
      @merge_request.unlock_mr
      @merge_request.close
    end
  end

447
448
449
  # Discussion tab data is rendered on html responses of actions
  # :show, :diff, :commits, :builds. but not when request the data through AJAX
  def define_discussion_vars
450
    # Build a note object for comment form
451
    @note = @project.notes.new(noteable: @merge_request)
452

453
    @discussions = @merge_request.discussions
454

455
456
    preload_noteable_for_regular_notes(@discussions.flat_map(&:notes))

457
    # This is not executed lazily
458
    @notes = Banzai::NoteRenderer.render(
459
      @discussions.flat_map(&:notes),
460
461
462
463
464
465
      @project,
      current_user,
      @path,
      @project_wiki,
      @ref
    )
466

Stan Hu's avatar
Stan Hu committed
467
    preload_max_access_for_authors(@notes, @project)
468
469
  end

470
  def define_widget_vars
471
472
    @pipeline = @merge_request.pipeline
    @pipelines = [@pipeline].compact
473
474
  end

475
476
477
478
479
480
481
482
483
484
485
  def define_commit_vars
    @commit = @merge_request.diff_head_commit
    @base_commit = @merge_request.diff_base_commit || @merge_request.likely_diff_base_commit
  end

  def define_diff_comment_vars
    @comments_target = {
      noteable_type: 'MergeRequest',
      noteable_id: @merge_request.id
    }

486
    @use_legacy_diff_notes = !@merge_request.has_complete_diff_refs?
487
    @grouped_diff_discussions = @merge_request.notes.inc_relations_for_view.grouped_diff_discussions
488
489

    Banzai::NoteRenderer.render(
490
      @grouped_diff_discussions.values.flat_map(&:notes),
491
492
493
494
495
496
497
498
      @project,
      current_user,
      @path,
      @project_wiki,
      @ref
    )
  end

499
500
501
502
503
  def invalid_mr
    # Render special view for MR with removed source or target branch
    render 'invalid'
  end

504
  def merge_request_params
505
    params.require(:merge_request).permit(
506
507
      :title, :assignee_id, :source_project_id, :source_branch,
      :target_project_id, :target_branch, :milestone_id,
508
      :state_event, :description, :task_num, :force_remove_source_branch,
509
      :lock_version, label_ids: []
510
511
    )
  end
512

513
514
515
516
  def merge_params
    params.permit(:should_remove_source_branch, :commit_message)
  end

517
518
519
520
521
  # Make sure merge requests created before 8.0
  # have head file in refs/merge-requests/
  def ensure_ref_fetched
    @merge_request.ensure_ref_fetched
  end
522
523
524
525
526

  def merge_when_build_succeeds_active?
    params[:merge_when_build_succeeds].present? &&
      @merge_request.pipeline && @merge_request.pipeline.active?
  end
527
528
529
530
531

  def build_merge_request
    params[:merge_request] ||= ActionController::Parameters.new(source_project: @project)
    @merge_request = MergeRequests::BuildService.new(project, current_user, merge_request_params).execute
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
532
end