Class: Danger::RequestSources::GitLab

Inherits:
RequestSource show all
Includes:
Helpers::CommentsHelper
Defined in:
lib/danger/request_sources/gitlab.rb

Constant Summary collapse

FIRST_GITLAB_GEM_WITH_VERSION_CHECK =
Gem::Version.new("4.6.0")
FIRST_VERSION_WITH_INLINE_COMMENTS =
Gem::Version.new("10.8.0")

Constants inherited from RequestSource

RequestSource::DANGER_REPO_NAME

Instance Attribute Summary collapse

Attributes inherited from RequestSource

#ci_source, #environment, #ignored_violations

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Helpers::CommentsHelper

#apply_template, #generate_comment, #generate_description, #generate_inline_comment_body, #generate_inline_markdown_body, #markdown_link_to_message, #markdown_parser, #messages_are_equivalent, #process_markdown, #random_compliment, #table

Methods included from Helpers::CommentsParsingHelper

#parse_comment, #parse_message_from_row, #parse_tables_from_comment, #table_kind_from_title, #violations_from_table

Methods inherited from RequestSource

available_request_sources, available_source_names_and_envs, inherited, source_name

Constructor Details

#initialize(ci_source, environment) ⇒ GitLab

Returns a new instance of GitLab.



24
25
26
27
28
29
# File 'lib/danger/request_sources/gitlab.rb', line 24

def initialize(ci_source, environment)
  self.ci_source = ci_source
  self.environment = environment

  @token = @environment["DANGER_GITLAB_API_TOKEN"]
end

Instance Attribute Details

#commits_jsonObject

Returns the value of attribute commits_json.



11
12
13
# File 'lib/danger/request_sources/gitlab.rb', line 11

def commits_json
  @commits_json
end

#mr_jsonObject

Returns the value of attribute mr_json.



11
12
13
# File 'lib/danger/request_sources/gitlab.rb', line 11

def mr_json
  @mr_json
end

Class Method Details

.env_varsObject



16
17
18
# File 'lib/danger/request_sources/gitlab.rb', line 16

def self.env_vars
  ["DANGER_GITLAB_API_TOKEN"]
end

.optional_env_varsObject



20
21
22
# File 'lib/danger/request_sources/gitlab.rb', line 20

def self.optional_env_vars
  ["DANGER_GITLAB_HOST", "DANGER_GITLAB_API_BASE_URL"]
end

Instance Method Details

#base_commitObject



68
69
70
# File 'lib/danger/request_sources/gitlab.rb', line 68

def base_commit
  @base_commit ||= self.mr_json.diff_refs.base_sha
end

#clientObject



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/danger/request_sources/gitlab.rb', line 31

def client
  token = @environment["DANGER_GITLAB_API_TOKEN"]
  raise "No API token given, please provide one using `DANGER_GITLAB_API_TOKEN`" unless token

  # The require happens inline so that it won't cause exceptions when just using the `danger` gem.
  require "gitlab"

  @client ||= Gitlab.client(endpoint: endpoint, private_token: token)
rescue LoadError
  puts "The GitLab gem was not installed, you will need to change your Gem from `danger` to `danger-gitlab`.".red
  puts "\n - See https://github.com/danger/danger/blob/master/CHANGELOG.md#400"
  abort
end

#delete_old_comments!(except: nil, danger_id: "danger") ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/danger/request_sources/gitlab.rb', line 261

def delete_old_comments!(except: nil, danger_id: "danger")
  @raw_comments.each do |raw_comment|

    comment = Comment.from_gitlab(raw_comment)
    next unless comment.generated_by_danger?(danger_id)
    next if comment.id == except
    next unless raw_comment.is_a?(Hash) && raw_comment["position"].nil?

    begin
      client.delete_merge_request_comment(
        ci_source.repo_slug,
        ci_source.pull_request_id,
        comment.id
      )
    rescue
    end
  end
end

#endpointObject



60
61
62
# File 'lib/danger/request_sources/gitlab.rb', line 60

def endpoint
  @endpoint ||= @environment["DANGER_GITLAB_API_BASE_URL"] || @environment["CI_API_V4_URL"] || "https://gitlab.com/api/v4"
end

#fetch_detailsObject



130
131
132
133
# File 'lib/danger/request_sources/gitlab.rb', line 130

def fetch_details
  self.mr_json = client.merge_request(ci_source.repo_slug, self.ci_source.pull_request_id)
  self.ignored_violations = ignored_violations_from_pr
end

#file_url(organisation: nil, repository: nil, branch: nil, path: nil) ⇒ String

Returns A URL to the specific file, ready to be downloaded.

Returns:

  • (String)

    A URL to the specific file, ready to be downloaded



286
287
288
289
290
# File 'lib/danger/request_sources/gitlab.rb', line 286

def file_url(organisation: nil, repository: nil, branch: nil, path: nil)
  branch ||= 'master'

  "https://#{host}/#{organisation}/#{repository}/raw/#{branch}/#{path}"
end

#hostObject



64
65
66
# File 'lib/danger/request_sources/gitlab.rb', line 64

def host
  @host ||= @environment["DANGER_GITLAB_HOST"] || URI.parse(endpoint).host || "gitlab.com"
end

#ignored_violations_from_prObject



135
136
137
# File 'lib/danger/request_sources/gitlab.rb', line 135

def ignored_violations_from_pr
  GetIgnoredViolation.new(self.mr_json.description).call
end

#inline_violations_group(warnings: [], errors: [], messages: [], markdowns: []) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/danger/request_sources/gitlab.rb', line 301

def inline_violations_group(warnings: [], errors: [], messages: [], markdowns: [])
  cmp = proc do |a, b|
    next -1 unless a.file && a.line
    next 1 unless b.file && b.line

    next a.line <=> b.line if a.file == b.file
    next a.file <=> b.file
  end

  # Sort to group inline comments by file
  {
    warnings: warnings.select(&:inline?).sort(&cmp),
    errors: errors.select(&:inline?).sort(&cmp),
    messages: messages.select(&:inline?).sort(&cmp),
    markdowns: markdowns.select(&:inline?).sort(&cmp)
  }
end

#merge_violations(*violation_groups) ⇒ Object



319
320
321
322
323
# File 'lib/danger/request_sources/gitlab.rb', line 319

def merge_violations(*violation_groups)
  violation_groups.inject({}) do |accumulator, group|
    accumulator.merge(group) { |_, old, fresh| old + fresh }
  end
end

#mr_changed_pathsObject



98
99
100
101
102
103
104
105
# File 'lib/danger/request_sources/gitlab.rb', line 98

def mr_changed_paths
  @mr_changed_paths ||= begin
    mr_changes
      .changes.map { |change| change["new_path"] }
  end

  @mr_changed_paths
end

#mr_changesObject



107
108
109
110
111
# File 'lib/danger/request_sources/gitlab.rb', line 107

def mr_changes
  @mr_changes ||= begin
    client.merge_request_changes(ci_source.repo_slug, ci_source.pull_request_id)
  end
end

#mr_commentsObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/danger/request_sources/gitlab.rb', line 72

def mr_comments
  # @raw_comments contains what we got back from the server.
  # @comments contains Comment objects (that have less information)
  @comments ||= begin
    if supports_inline_comments
      @raw_comments = client.merge_request_discussions(ci_source.repo_slug, ci_source.pull_request_id)
        .auto_paginate
        .flat_map { |discussion| discussion.notes.map { |note| note.merge({"discussion_id" => discussion.id}) } }
      @raw_comments
        .map { |comment| Comment.from_gitlab(comment) }
    else
      @raw_comments = client.merge_request_comments(ci_source.repo_slug, ci_source.pull_request_id, per_page: 100)
        .auto_paginate
      @raw_comments
        .map { |comment| Comment.from_gitlab(comment) }
    end
  end
end

#mr_diffObject



91
92
93
94
95
96
# File 'lib/danger/request_sources/gitlab.rb', line 91

def mr_diff
  @mr_diff ||= begin
    mr_changes
      .changes.map { |change| change["diff"] }.join("\n")
  end
end

#organisationString

Returns The organisation name, is nil if it can’t be detected.

Returns:

  • (String)

    The organisation name, is nil if it can’t be detected



281
282
283
# File 'lib/danger/request_sources/gitlab.rb', line 281

def organisation
  nil # TODO: Implement this
end

#regular_violations_group(warnings: [], errors: [], messages: [], markdowns: []) ⇒ Object



292
293
294
295
296
297
298
299
# File 'lib/danger/request_sources/gitlab.rb', line 292

def regular_violations_group(warnings: [], errors: [], messages: [], markdowns: [])
  {
    warnings: warnings.reject(&:inline?),
    errors: errors.reject(&:inline?),
    messages: messages.reject(&:inline?),
    markdowns: markdowns.reject(&:inline?)
  }
end

#scmObject



56
57
58
# File 'lib/danger/request_sources/gitlab.rb', line 56

def scm
  @scm ||= GitRepo.new
end

#setup_danger_branchesObject



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/danger/request_sources/gitlab.rb', line 113

def setup_danger_branches
  base_branch = self.mr_json.source_branch
  head_branch = self.mr_json.target_branch
  head_commit = self.scm.head_commit

  raise "Are you running `danger local/pr` against the correct repository? Also this can happen if you run danger on MR without changes" if base_commit == head_commit

  # Next, we want to ensure that we have a version of the current branch at a known location
  scm.ensure_commitish_exists_on_branch! base_branch, base_commit
  self.scm.exec "branch #{EnvironmentManager.danger_base_branch} #{base_commit}"

  # OK, so we want to ensure that we have a known head branch, this will always represent
  # the head of the PR ( e.g. the most recent commit that will be merged. )
  scm.ensure_commitish_exists_on_branch! head_branch, head_commit
  self.scm.exec "branch #{EnvironmentManager.danger_head_branch} #{head_commit}"
end

#submit_inline_comments!(warnings: [], errors: [], messages: [], markdowns: [], previous_violations: [], danger_id: "danger") ⇒ Object



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/danger/request_sources/gitlab.rb', line 325

def submit_inline_comments!(warnings: [], errors: [], messages: [], markdowns: [], previous_violations: [], danger_id: "danger")
  comments = client.merge_request_discussions(ci_source.repo_slug, ci_source.pull_request_id)
    .auto_paginate
    .flat_map { |discussion| discussion.notes.map { |note| note.merge({"discussion_id" => discussion.id}) } }

  danger_comments = comments.select { |comment| Comment.from_gitlab(comment).generated_by_danger?(danger_id) }
  non_danger_comments = comments - danger_comments

  diff_lines = []

  warnings = submit_inline_comments_for_kind!(:warning, warnings, diff_lines, danger_comments, previous_violations["warning"], danger_id: danger_id)
  errors = submit_inline_comments_for_kind!(:error, errors, diff_lines, danger_comments, previous_violations["error"], danger_id: danger_id)
  messages = submit_inline_comments_for_kind!(:message, messages, diff_lines, danger_comments, previous_violations["message"], danger_id: danger_id)
  markdowns = submit_inline_comments_for_kind!(:markdown, markdowns, diff_lines, danger_comments, [], danger_id: danger_id)

  # submit removes from the array all comments that are still in force
  # so we strike out all remaining ones
  danger_comments.each do |comment|
    violation = violations_from_table(comment["body"]).first
    if !violation.nil? && violation.sticky
      body = generate_inline_comment_body("white_check_mark", violation, danger_id: danger_id, resolved: true, template: "gitlab")
      client.update_merge_request_discussion_note(ci_source.repo_slug, ci_source.pull_request_id, comment["discussion_id"], comment["id"], body)
    else
      # We remove non-sticky violations that have no replies
      # Since there's no direct concept of a reply in GH, we simply consider
      # the existance of non-danger comments in that line as replies
      replies = non_danger_comments.select do |potential|
        potential["path"] == comment["path"] &&
          potential["position"] == comment["position"] &&
          potential["commit_id"] == comment["commit_id"]
      end

      client.delete_merge_request_comment(ci_source.repo_slug, ci_source.pull_request_id, comment["id"]) if replies.empty?
    end
  end

  {
    warnings: warnings,
    errors: errors,
    messages: messages,
    markdowns: markdowns
  }
end

#submit_inline_comments_for_kind!(kind, messages, diff_lines, danger_comments, previous_violations, danger_id: "danger") ⇒ Object



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/danger/request_sources/gitlab.rb', line 369

def submit_inline_comments_for_kind!(kind, messages, diff_lines, danger_comments, previous_violations, danger_id: "danger")
  previous_violations ||= []
  is_markdown_content = kind == :markdown
  emoji = { warning: "warning", error: "no_entry_sign", message: "book" }[kind]

  messages.reject do |m|
    next false unless m.file && m.line

    # Keep the change it's in a file changed in this diff
    next if !mr_changed_paths.include?(m.file)

    # Once we know we're gonna submit it, we format it
    if is_markdown_content
      body = generate_inline_markdown_body(m, danger_id: danger_id, template: "gitlab")
    else
      # Hide the inline link behind a span
      m = process_markdown(m, true)
      body = generate_inline_comment_body(emoji, m, danger_id: danger_id, template: "gitlab")
      # A comment might be in previous_violations because only now it's part of the unified diff
      # We remove from the array since it won't have a place in the table anymore
      previous_violations.reject! { |v| messages_are_equivalent(v, m) }
    end

    matching_comments = danger_comments.select do |comment_data|
      position = comment_data["position"]

      if position.nil?
        false
      else
        position["new_path"] == m.file && position["new_line"] == m.line
      end
    end

    if matching_comments.empty?
      params = {
        body: body,
        position: {
          position_type: 'text',
          new_path: m.file,
          new_line: m.line,
          base_sha: self.mr_json.diff_refs.base_sha,
          start_sha: self.mr_json.diff_refs.start_sha,
          head_sha: self.mr_json.diff_refs.head_sha
        }
      }
      begin
        client.create_merge_request_discussion(ci_source.repo_slug, ci_source.pull_request_id, params)
      rescue Gitlab::Error::Error => e
        message = [e, "body: #{body}", "position: #{params[:position].inspect}"].join("\n")
        puts message

        next false
      end
    else
      # Remove the surviving comment so we don't strike it out
      danger_comments.reject! { |c| matching_comments.include? c }

      # Update the comment to remove the strikethrough if present
      comment = matching_comments.first
      begin
        client.update_merge_request_discussion_note(ci_source.repo_slug, ci_source.pull_request_id, comment["discussion_id"], comment["id"], body)
      rescue Gitlab::Error::Error => e
        message = [e, "body: #{body}"].join("\n")
        puts message
        
        next false
      end
    end

    # Remove this element from the array
    next true
  end
end

#supports_inline_commentsObject



139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/danger/request_sources/gitlab.rb', line 139

def supports_inline_comments
  @supports_inline_comments ||= begin
    # If we can't check GitLab's version, we assume we don't support inline comments
    if Gem.loaded_specs["gitlab"].version < FIRST_GITLAB_GEM_WITH_VERSION_CHECK
      false
    else
      current_version = Gem::Version.new(client.version.version)

      current_version >= FIRST_VERSION_WITH_INLINE_COMMENTS
    end
  end
end

#update_pull_request!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger", new_comment: false, remove_previous_comments: false) ⇒ Object



152
153
154
155
156
157
158
# File 'lib/danger/request_sources/gitlab.rb', line 152

def update_pull_request!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger", new_comment: false, remove_previous_comments: false)
  if supports_inline_comments
    update_pull_request_with_inline_comments!(warnings: warnings, errors: errors, messages: messages, markdowns: markdowns, danger_id: danger_id, new_comment: new_comment, remove_previous_comments: remove_previous_comments)
  else
    update_pull_request_without_inline_comments!(warnings: warnings, errors: errors, messages: messages, markdowns: markdowns, danger_id: danger_id, new_comment: new_comment, remove_previous_comments: remove_previous_comments)
  end
end

#update_pull_request_with_inline_comments!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger", new_comment: false, remove_previous_comments: false) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/danger/request_sources/gitlab.rb', line 160

def update_pull_request_with_inline_comments!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger", new_comment: false, remove_previous_comments: false)
  editable_comments = mr_comments.select { |comment| comment.generated_by_danger?(danger_id) }

  last_comment = editable_comments.last
  should_create_new_comment = new_comment || last_comment.nil? || remove_previous_comments

  previous_violations =
    if should_create_new_comment
      {}
    else
      parse_comment(last_comment.body)
    end

  regular_violations = regular_violations_group(
    warnings: warnings,
    errors: errors,
    messages: messages,
    markdowns: markdowns
  )

  inline_violations = inline_violations_group(
    warnings: warnings,
    errors: errors,
    messages: messages,
    markdowns: markdowns
  )

  rest_inline_violations = submit_inline_comments!({
    danger_id: danger_id,
    previous_violations: previous_violations
  }.merge(inline_violations))

  main_violations = merge_violations(
    regular_violations, rest_inline_violations
  )

  main_violations_sum = main_violations.values.inject(:+)

  if (previous_violations.empty? && main_violations_sum.empty?) || remove_previous_comments
    # Just remove the comment, if there's nothing to say or --remove-previous-comments CLI was set.
    delete_old_comments!(danger_id: danger_id)
  end

  # If there are still violations to show
  if main_violations_sum.any?
    body = generate_comment({
      template: "gitlab",
      danger_id: danger_id,
      previous_violations: previous_violations
    }.merge(main_violations))

    comment_result =
      if should_create_new_comment
        client.create_merge_request_note(ci_source.repo_slug, ci_source.pull_request_id, body)
      else
        client.edit_merge_request_note(ci_source.repo_slug, ci_source.pull_request_id, last_comment.id, body)
      end
  end
  
end

#update_pull_request_without_inline_comments!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger", new_comment: false, remove_previous_comments: false) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/danger/request_sources/gitlab.rb', line 221

def update_pull_request_without_inline_comments!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger", new_comment: false, remove_previous_comments: false)
  editable_comments = mr_comments.select { |comment| comment.generated_by_danger?(danger_id) }

  should_create_new_comment = new_comment || editable_comments.empty? || remove_previous_comments

  if should_create_new_comment
    previous_violations = {}
  else
    comment = editable_comments.first.body
    previous_violations = parse_comment(comment)
  end

  if (previous_violations.empty? && (warnings + errors + messages + markdowns).empty?) || remove_previous_comments
    # Just remove the comment, if there's nothing to say or --remove-previous-comments CLI was set.
    delete_old_comments!(danger_id: danger_id)
  else
    body = generate_comment(warnings: warnings,
                              errors: errors,
                            messages: messages,
                           markdowns: markdowns,
                 previous_violations: previous_violations,
                           danger_id: danger_id,
                            template: "gitlab")

    if editable_comments.empty? or should_create_new_comment
      client.create_merge_request_comment(
        ci_source.repo_slug, ci_source.pull_request_id, body
      )
    else
      original_id = editable_comments.first.id
      client.edit_merge_request_comment(
        ci_source.repo_slug,
        ci_source.pull_request_id,
        original_id,
        { body: body }
      )
    end
  end
end

#validates_as_api_source?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/danger/request_sources/gitlab.rb', line 52

def validates_as_api_source?
  @token && !@token.empty?
end

#validates_as_ci?Boolean

Returns:

  • (Boolean)


45
46
47
48
49
50
# File 'lib/danger/request_sources/gitlab.rb', line 45

def validates_as_ci?
  includes_port = self.host.include? ":"
  raise "Port number included in `DANGER_GITLAB_HOST`, this will fail with GitLab CI Runners" if includes_port

  super
end