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

module Ci
  class SlackMessage
    include Gitlab::Application.routes.url_helpers

    def initialize(commit)
      @commit = commit
    end

    def pretext
      ''
    end

    def color
      attachment_color
    end

    def fallback
      format(attachment_message)
    end

    def attachments
      fields = []

      commit.latest_builds.each do |build|
        next if build.allow_failure?
        next unless build.failed?
        fields << {
          title: build.name,
          value: "Build <#{namespace_project_build_url(build.gl_project.namespace, build.gl_project, build)}|\##{build.id}> failed in #{build.duration.to_i} second(s)."
        }
      end

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

    private

    attr_reader :commit

    def attachment_message
      out = "<#{ci_project_url(project)}|#{project_name}>: "
      out << "Commit <#{ci_namespace_project_commit_url(commit.gl_project.namespace, commit.gl_project, commit.sha)}|\##{commit.id}> "
      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