Skip to content

Instantly share code, notes, and snippets.

@zealot128
Created September 10, 2020 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zealot128/297beb739b817b732d0e3e86857aa59c to your computer and use it in GitHub Desktop.
Save zealot128/297beb739b817b732d0e3e86857aa59c to your computer and use it in GitHub Desktop.
Gitlab: Auto-Close all empty stale Merge-Requests
# Auto-Close all open MR's that:
# - are created before 3 months
# - have NO changes (no commits pushed)
# - has a issue attached that is already closed
#
# Background: Gitlab makes it easy to create a MR for a issue via button.
# But sometimes that branch becomes stale and the issue will be moved/fixed differently
#
# Afterwards, also triggers a Remove Merged Branches Job
# DANGER: Use on your own discretion
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'gitlab'
end
require 'gitlab'
Gitlab.endpoint = URL
Gitlab.private_token = TOKEN
min_age = 3.months.ago.to_date
my_mr = Gitlab.user_merge_requests(state: :opened, scope: :all, created_before: min_age.to_s).auto_paginate
projects_with_changes = []
my_mr.each do |mr|
skip_reasons = []
changes_count = Gitlab.merge_request(mr.project_id, mr.iid).as_json['changes_count']
if changes_count != nil
skip_reasons << "Has Changes attached #{changes_count}"
end
issues = Gitlab.merge_request_closes_issues(mr.project_id, mr.iid)
if issues.count == 0
skip_reasons << "No Issues referenced"
end
unless issues.all? { |i| i.state == 'closed'}
skip_reasons << "Has unclosed issues"
end
if skip_reasons.any?
puts "SKIPPING #{mr.web_url} - #{skip_reasons.join(' | ')}"
next
end
puts "CLOSING #{mr.web_url}"
Gitlab.update_merge_request(mr.project_id, mr.iid, state_event: 'close')
projects_with_changes << mr.project_id
rescue Gitlab::Error::Forbidden => e
puts "ERROR: Cannot access gitlab: #{e}"
end
projects_with_changes.each do |project_id|
Gitlab.delete_merged_branches(project_id)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment