summaryrefslogtreecommitdiff
path: root/lib/api/suggestions.rb
blob: 6260983087fc4fb6415c6392e4d05eb1d88658a5 (plain)
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
# frozen_string_literal: true

module API
  class Suggestions < ::API::Base
    before { authenticate! }

    feature_category :code_review

    resource :suggestions do
      desc 'Apply suggestion patch in the Merge Request it was created' do
        success Entities::Suggestion
        tags %w[suggestions]
      end
      params do
        requires :id, type: Integer, desc: 'The ID of the suggestion'
        optional :commit_message, type: String, desc: "A custom commit message to use instead of the default generated message or the project's default message"
      end
      put ':id/apply', urgency: :low do
        suggestion = Suggestion.find_by_id(params[:id])

        if suggestion
          apply_suggestions(suggestion, current_user, params[:commit_message])
        else
          render_api_error!(_('Suggestion is not applicable as the suggestion was not found.'), :not_found)
        end
      end

      desc 'Apply multiple suggestion patches in the Merge Request where they were created' do
        success Entities::Suggestion
        tags %w[suggestions]
      end
      params do
        requires :ids, type: Array[Integer], coerce_with: ::API::Validations::Types::CommaSeparatedToIntegerArray.coerce, desc: "An array of the suggestion IDs"
        optional :commit_message, type: String, desc: "A custom commit message to use instead of the default generated message or the project's default message"
      end
      put 'batch_apply', urgency: :low do
        ids = params[:ids]

        suggestions = Suggestion.id_in(ids)

        if suggestions.size == ids.length
          apply_suggestions(suggestions, current_user, params[:commit_message])
        else
          render_api_error!(_('Suggestions are not applicable as one or more suggestions were not found.'), :not_found)
        end
      end
    end

    helpers do
      def apply_suggestions(suggestions, current_user, message)
        authorize_suggestions(*suggestions)

        result = ::Suggestions::ApplyService.new(current_user, *suggestions, message: message).execute

        if result[:status] == :success
          present suggestions, with: Entities::Suggestion, current_user: current_user
        else
          http_status = result[:http_status] || :bad_request
          render_api_error!(result[:message], http_status)
        end
      end

      def authorize_suggestions(*suggestions)
        suggestions.each do |suggestion|
          authorize! :apply_suggestion, suggestion
        end
      end
    end
  end
end