class Danger::DangerGitlabCancelbot

Cancels all redunant pipelines for the current merge request @example Cancelling all redunant pipelines for the current merge request

# Runs a linter with comma style and tense present disabled
gitlab_cancelbot.cancel_redundant_pipelines!

@see Fabio Gallonetto/danger-gitlab_cancelbot @tags cancel, gitlab, pipelines

Public Instance Methods

cancel_redundant_pipelines!() click to toggle source

Call this method from the Dangerfile to cancel obsolete pipelines running for the same merge request

@return The IDs of the cancelled pipelines [Array<Int>]

# File lib/gitlab_cancelbot/plugin.rb, line 20
def cancel_redundant_pipelines!
  project_id = ENV["CI_PROJECT_ID"]
  mr_iid = ENV["CI_MERGE_REQUEST_IID"]
  if mr_iid.nil?
    raise "Env variable CI_MERGE_REQUEST_IID doesn't point to a valid merge request iid"
  end

  if project_id.nil?
    raise "Env variable CI_PROJECT_ID doesn't point to a valid project id"
  end

  project_id = project_id.to_i
  mr_iid = mr_iid.to_i

  running_pipelines = gitlab.api.running_pipelines_for_mr(project_id, mr_iid).sort_by(&:created_at)

  puts "Found #{running_pipelines.length} for MR ##{mr_iid}" if verbose
  if running_pipelines.length > 1
    running_pipelines.pop
    running_pipelines.each { |p| gitlab.api.cancel_pipeline(project_id, p.id) }
  end

  cancelled_ids = running_pipelines.map(&:id)
  puts "Cancelled the following obsolete pipelines: #{cancelled_ids}" if verbose

  return cancelled_ids
end