Sha256: ea87ed57422c6d9f4bb0db447ed9c08b09e4f35e139d51378eb8638d6612964e

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 KB

Contents

# frozen_string_literal: true

require "gitlab_cancelbot/gitlab"

module Danger
  # 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
  #
  class DangerGitlabCancelbot < Plugin
    # Add verbosity to the logs
    #
    # @return  Bool
    attr_accessor :verbose

    # 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>]
    #
    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
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
danger-gitlab_cancelbot-1.0.0 lib/gitlab_cancelbot/plugin.rb