BigW Consortium Gitlab

slack_message.rb 2.14 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
require 'slack-notifier'

class SlackMessage
  def initialize(params)
    @after = params.fetch(:after)
    @before = params.fetch(:before)
    @commits = params.fetch(:commits, [])
    @project_name = params.fetch(:project_name)
    @project_url = params.fetch(:project_url)
    @ref = params.fetch(:ref).gsub('refs/heads/', '')
    @username = params.fetch(:user_name)
  end

14
  def pretext
15 16 17
    format(message)
  end

18 19 20 21 22 23
  def attachments
    return [] if new_branch? || removed_branch?

    commit_message_attachments
  end

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
  private

  attr_reader :after
  attr_reader :before
  attr_reader :commits
  attr_reader :project_name
  attr_reader :project_url
  attr_reader :ref
  attr_reader :username

  def message
    if new_branch?
      new_branch_message
    elsif removed_branch?
      removed_branch_message
    else
40
      push_message
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    end
  end

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

  def new_branch_message
    "#{username} pushed new branch #{branch_link} to #{project_link}"
  end

  def removed_branch_message
    "#{username} removed branch #{ref} from #{project_link}"
  end

  def push_message
    "#{username} pushed to branch #{branch_link} of #{project_link} (#{compare_link})"
  end

  def commit_messages
    commits.each_with_object('') do |commit, str|
      str << compose_commit_message(commit)
63 64 65 66 67
    end.chomp
  end

  def commit_message_attachments
    [{ text: format(commit_messages), color: attachment_color }]
68 69 70
  end

  def compose_commit_message(commit)
71 72
    author = commit.fetch(:author).fetch(:name)
    id = commit.fetch(:id)[0..8]
73 74 75
    message = commit.fetch(:message)
    url = commit.fetch(:url)

76
    "[#{id}](#{url}): #{message} - #{author}\n"
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
  end

  def new_branch?
    before =~ /000000/
  end

  def removed_branch?
    after =~ /000000/
  end

  def branch_url
    "#{project_url}/commits/#{ref}"
  end

  def compare_url
    "#{project_url}/compare/#{before}...#{after}"
  end

  def branch_link
    "[#{ref}](#{branch_url})"
  end

  def project_link
    "[#{project_name}](#{project_url})"
  end

  def compare_link
    "[Compare changes](#{compare_url})"
  end
106 107 108 109

  def attachment_color
    '#345'
  end
110
end