Skip to content

Instantly share code, notes, and snippets.

@halloffame
Created August 27, 2021 19:40
Show Gist options
  • Save halloffame/c953e44e9cf1fa3ca22ce71f08c23fdd to your computer and use it in GitHub Desktop.
Save halloffame/c953e44e9cf1fa3ca22ce71f08c23fdd to your computer and use it in GitHub Desktop.
Ruby script to delete *-site branches older than X days
#!/usr/bin/env ruby
require 'octokit'
REPO = ENV["GITHUB_REPO"]
ACCESS_TOKEN = ENV["GITHUB_ACCESS_TOKEN"]
DELETE_OLDER_THAN_DAYS = ENV["DELETE_OLDER_THAN_DAYS"].to_i
DOIT = ENV["DOIT"] == "true"
client = Octokit::Client.new(access_token: ACCESS_TOKEN)
client.auto_paginate = true
branches = client.branches(REPO)
branches.each do |branch|
# Skip protected branches
next if branch[:protected]
# We only want to delete *-site branches
next unless branch[:name].match?(/-site$/)
# Get the parent branch
parent_branch_name = branch[:name].gsub(/-site$/, "")
parent_branch = branches.find { |b| b[:name] === parent_branch_name }
# Skip if the parent branch exists
# we only want to delete branches that don't have parents
next if branches.include?(parent_branch)
if DELETE_OLDER_THAN_DAYS && DELETE_OLDER_THAN_DAYS > 0
# Branch doesn't contain date, so we have to look it up in the latest commit.
commit = client.commit(REPO, branch[:commit][:sha])
# Skip if PR was worked on in the last X days
next unless commit[:commit][:author][:date] < Time.now - (3600 * 24 * DELETE_OLDER_THAN_DAYS)
end
if DOIT
puts "Deleting branch: #{branch[:name]}"
client.delete_branch(REPO, branch[:name])
else
puts "[DRY RUN] Deleting branch: #{branch[:name]}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment