summaryrefslogtreecommitdiff
path: root/app/models/project_services/ci/slack_message.rb
blob: 7d884849bf3ce8e7953822d6fa008227c305273e (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
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
require 'slack-notifier'

module Ci
  class SlackMessage
    def initialize(commit)
      @commit = commit
    end

    def pretext
      ''
    end

    def color
      attachment_color
    end

    def fallback
      format(attachment_message)
    end

    def attachments
      fields = []

      if commit.matrix?
        commit.builds_without_retry.each do |build|
          next if build.allow_failure?
          next unless build.failed?
          fields << {
            title: build.name,
            value: "Build <#{Ci::RoutesHelper.ci_project_build_url(project, build)}|\##{build.id}> failed in #{build.duration.to_i} second(s)."
          }
        end
      end

      [{
         text: attachment_message,
         color: attachment_color,
         fields: fields
       }]
    end

    private

    attr_reader :commit

    def attachment_message
      out = "<#{Ci::RoutesHelper.ci_project_url(project)}|#{project_name}>: "
      if commit.matrix?
        out << "Commit <#{Ci::RoutesHelper.ci_project_ref_commit_url(project, commit.ref, commit.sha)}|\##{commit.id}> "
      else
        build = commit.builds_without_retry.first
        out << "Build <#{Ci::RoutesHelper.ci_project_build_url(project, build)}|\##{build.id}> "
      end
      out << "(<#{commit_sha_link}|#{commit.short_sha}>) "
      out << "of <#{commit_ref_link}|#{commit.ref}> "
      out << "by #{commit.git_author_name} " if commit.git_author_name
      out << "#{commit_status} in "
      out << "#{commit.duration} second(s)"
    end

    def format(string)
      Slack::Notifier::LinkFormatter.format(string)
    end

    def project
      commit.project
    end

    def project_name
      project.name
    end

    def commit_sha_link
      "#{project.gitlab_url}/commit/#{commit.sha}"
    end

    def commit_ref_link
      "#{project.gitlab_url}/commits/#{commit.ref}"
    end

    def attachment_color
      if commit.success?
        'good'
      else
        'danger'
      end
    end

    def commit_status
      if commit.success?
        'succeeded'
      else
        'failed'
      end
    end
  end
end