slack_message.rb 1.89 KB
Newer Older
1 2 3 4
require 'slack-notifier'

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

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
    def initialize(commit)
      @commit = commit
    end

    def pretext
      ''
    end

    def color
      attachment_color
    end

    def fallback
      format(attachment_message)
    end

    def attachments
      fields = []

26
      commit.latest_builds.each do |build|
Kamil Trzcinski's avatar
Kamil Trzcinski committed
27 28 29 30
        next if build.allow_failure?
        next unless build.failed?
        fields << {
          title: build.name,
31
          value: "Build <#{namespace_project_build_url(build.gl_project.namespace, build.gl_project, build)}|\##{build.id}> failed in #{build.duration.to_i} second(s)."
Kamil Trzcinski's avatar
Kamil Trzcinski committed
32
        }
33 34 35 36 37 38 39 40 41 42 43 44 45 46
      end

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

    private

    attr_reader :commit

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