summaryrefslogtreecommitdiff
path: root/lib/gitlab/suggestions/commit_message.rb
blob: 5bca3efe6e1c82aefda0061b7c9e4af2dd1ffca6 (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
# frozen_string_literal: true

module Gitlab
  module Suggestions
    class CommitMessage
      DEFAULT_SUGGESTION_COMMIT_MESSAGE =
        'Apply %{suggestions_count} suggestion(s) to %{files_count} file(s)'

      def initialize(user, suggestion_set, custom_message = nil)
        @user = user
        @suggestion_set = suggestion_set
        @custom_message = custom_message
      end

      def message
        project = suggestion_set.project
        user_defined_message = @custom_message.presence || project.suggestion_commit_message.presence
        message = user_defined_message || DEFAULT_SUGGESTION_COMMIT_MESSAGE

        Gitlab::StringPlaceholderReplacer
          .replace_string_placeholders(message, PLACEHOLDERS_REGEX) do |key|
          PLACEHOLDERS[key].call(user, suggestion_set)
        end
      end

      def self.format_paths(paths)
        paths.sort.join(', ')
      end

      private_class_method :format_paths

      private

      attr_reader :user, :suggestion_set

      PLACEHOLDERS = {
        'branch_name' => ->(user, suggestion_set) { suggestion_set.branch },
        'files_count' => ->(user, suggestion_set) { suggestion_set.file_paths.length },
        'file_paths' => ->(user, suggestion_set) { format_paths(suggestion_set.file_paths) },
        'project_name' => ->(user, suggestion_set) { suggestion_set.project.name },
        'project_path' => ->(user, suggestion_set) { suggestion_set.project.path },
        'user_full_name' => ->(user, suggestion_set) { user.name },
        'username' => ->(user, suggestion_set) { user.username },
        'suggestions_count' => ->(user, suggestion_set) { suggestion_set.suggestions.size }
      }.freeze

      # This regex is built dynamically using the keys from the PLACEHOLDER struct.
      # So, we can easily add new placeholder just by modifying the PLACEHOLDER hash.
      # This regex will build the new PLACEHOLDER_REGEX with the new information
      PLACEHOLDERS_REGEX = Regexp.union(PLACEHOLDERS.keys.map do |key|
        Regexp.new(Regexp.escape(key))
      end).freeze
    end
  end
end