Sha256: d8c804886bc93b05cd02f4f9d9d045a3bc4e75ee07c3f4b0a05364d981ece5f3

Contents?: true

Size: 1.84 KB

Versions: 2

Compression:

Stored size: 1.84 KB

Contents

require "gitlab"

module TerraspaceCiGitlab
  class Pr
    extend Memoist

    def comment(url)
      return unless ENV['CI_PIPELINE_SOURCE'] == 'merge_request_event'
      return unless gitlab_token?

      repo = ENV['CI_PROJECT_PATH'] # org/repo
      number = ENV['CI_MERGE_REQUEST_IID']
      marker = "<!-- terraspace marker -->"
      body = marker + "\n"
      body << "Terraspace Cloud Url #{url}"

      puts "Adding comment to repo #{repo} number #{number}"

      project = client.project(ENV['CI_PROJECT_PATH'])
      merge_request = ENV['CI_MERGE_REQUEST_IID']

      # https://www.rubydoc.info/gems/gitlab/Gitlab/Client/Notes
      # TODO: handle pagination
      notes = client.merge_request_notes(project.id, number)
      # TODO: handle not found. Examples:
      # token is not valid
      # token is not right repo
      # todo are we allow to post comment on public repo without need the permission?
      found_note = notes.find do |note|
        note.body.starts_with?(marker)
      end

      if found_note
        client.edit_merge_request_note(project.id, merge_request, found_note.id, body) unless found_note.body == body
      else
        client.create_merge_request_note(project.id, merge_request, body)
      end
    rescue Gitlab::Error::Unauthorized => e
      puts "WARN: #{e.message}. Unable to create merge request comment. Please double check your gitlab token"
    rescue Gitlab::Error::Forbidden => e
      puts "WARN: #{e.message}. Unable to create merge request comment. The token does not have the permission. Please double check your gitlab token"
    end

    def client
      Gitlab.configure do |config|
        config.endpoint       = 'https://gitlab.com/api/v4'
        config.private_token  = ENV['GITLAB_TOKEN']
      end
      Gitlab.client
    end
    memoize :client

    def gitlab_token?
      ENV['GITLAB_TOKEN']
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
terraspace_ci_gitlab-0.2.0 lib/terraspace_ci_gitlab/pr.rb
terraspace_ci_gitlab-0.1.1 lib/terraspace_ci_gitlab/pr.rb