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, #update_build_status

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



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/danger/request_sources/gitlab.rb', line 273

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



141
142
143
144
# File 'lib/danger/request_sources/gitlab.rb', line 141

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



298
299
300
301
302
# File 'lib/danger/request_sources/gitlab.rb', line 298

def file_url(organisation: nil, repository: nil, branch: nil, path: nil)
  branch ||= 'master'
  token = @environment["DANGER_GITLAB_API_TOKEN"]
  "#{endpoint}/projects/#{repository}/repository/files/#{path}/raw?ref=#{branch}&private_token=#{token}"
end

#find_old_position_in_diff(changes, message) ⇒ Object



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/danger/request_sources/gitlab.rb', line 461

def find_old_position_in_diff(changes, message)
  range_header_regexp = /@@ -(?<old>[0-9]+)(,([0-9]+))? \+(?<new>[0-9]+)(,([0-9]+))? @@.*/

  change = changes.find { |c| c["new_path"] == message.file }

  # If there is no changes or rename only or deleted, return nil.
  return nil if change.nil? || change["diff"].empty? || change["deleted_file"]

  modified_position = {
    path: change["old_path"],
    line: nil
  }

  # If the file is new one, old line number must be nil.
  return modified_position if change["new_file"]

  current_old_line = 0
  current_new_line = 0

  change["diff"].each_line do |line|
    match = line.match range_header_regexp

    if match
      # If the message line is at before next diffs, break from loop.
      break if message.line.to_i < match[:new].to_i

      # The match [:old] line does not appear yet at the header position, so reduce line number.
      current_old_line = match[:old].to_i - 1
      current_new_line = match[:new].to_i - 1
      next
    end

    if line.start_with?("-")
      current_old_line += 1
    elsif line.start_with?("+")
      current_new_line += 1
      # If the message line starts with '+', old line number must be nil.
      return modified_position if current_new_line == message.line.to_i
    elsif !line.eql?("\\ No newline at end of file\n")
      current_old_line += 1
      current_new_line += 1
      # If the message line doesn't start with '+', old line number must be specified.
      break if current_new_line == message.line.to_i
    end
  end

  {
    path: change["old_path"],
    line: current_old_line - current_new_line + message.line.to_i
  }
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



146
147
148
# File 'lib/danger/request_sources/gitlab.rb', line 146

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

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



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/danger/request_sources/gitlab.rb', line 313

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



331
332
333
334
335
# File 'lib/danger/request_sources/gitlab.rb', line 331

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

#mr_changed_pathsObject



109
110
111
112
113
114
115
116
# File 'lib/danger/request_sources/gitlab.rb', line 109

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

  @mr_changed_paths
end

#mr_changesObject



118
119
120
121
122
# File 'lib/danger/request_sources/gitlab.rb', line 118

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 = mr_discussions
        .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



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

def mr_diff
  @mr_diff ||= begin
    diffs = mr_changes.changes.map do |change|
      diff = change["diff"]
      if diff.start_with?('--- a/')
        diff
      else
        "--- a/#{change["old_path"]}\n+++ b/#{change["new_path"]}\n#{diff}"
      end
    end
    diffs.join("\n")
  end
end

#mr_discussionsObject



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

def mr_discussions
  @mr_discussions ||= client.merge_request_discussions(ci_source.repo_slug, ci_source.pull_request_id)
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



293
294
295
# File 'lib/danger/request_sources/gitlab.rb', line 293

def organisation
  nil # TODO: Implement this
end

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



304
305
306
307
308
309
310
311
# File 'lib/danger/request_sources/gitlab.rb', line 304

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



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/danger/request_sources/gitlab.rb', line 124

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



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
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/danger/request_sources/gitlab.rb', line 337

def submit_inline_comments!(warnings: [], errors: [], messages: [], markdowns: [], previous_violations: [], danger_id: "danger")
  comments = mr_discussions
    .auto_paginate
    .flat_map { |discussion| discussion.notes.map { |note| note.merge({"discussion_id" => discussion.id}) } }
    .select { |comment| Comment.from_gitlab(comment).inline? }

  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: 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 existence 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



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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/danger/request_sources/gitlab.rb', line 382

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?
      old_position = find_old_position_in_diff mr_changes.changes, m
      next false if old_position.nil?

      params = {
        body: body,
        position: {
          position_type: 'text',
          new_path: m.file,
          new_line: m.line,
          old_path: old_position[:path],
          old_line: old_position[: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: 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



150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/danger/request_sources/gitlab.rb', line 150

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



163
164
165
166
167
168
169
# File 'lib/danger/request_sources/gitlab.rb', line 163

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



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
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/danger/request_sources/gitlab.rb', line 171

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

  last_comment = editable_regular_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



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
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/danger/request_sources/gitlab.rb', line 233

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