Skip to content

Instantly share code, notes, and snippets.

@jjb
Last active December 16, 2024 19:35
Show Gist options
  • Save jjb/5d3d5d4127e77d79452d3619fa8a3c1b to your computer and use it in GitHub Desktop.
Save jjb/5d3d5d4127e77d79452d3619fa8a3c1b to your computer and use it in GitHub Desktop.
Script to delete old git branches
# frozen_string_literal: true
require 'time'
# Get the list of branches with their last commit date
branches = `git for-each-ref --format '%(refname:short) %(committerdate)' refs/heads/`
months_ago = 12
threshold = Time.now - (months_ago * 30 * 24 * 60 * 60)
branches_to_delete = {}
branches.each_line do |line|
branch, last_commit_date_str = line.split(' ', 2)
last_commit_date = Time.parse(last_commit_date_str.strip)
branches_to_delete[branch] = threshold if last_commit_date < threshold
end
unless branches_to_delete.any?
puts 'did not find any branches to delete!'
exit
end
puts "Last updated\tbranch"
branches_to_delete.each do |branch, date|
print date
print "\t"
puts branch
end
puts 'The above branches will be force-deleted. Hit enter to continue, control-c to cancel.'
gets
branches_to_delete.each_key do |branch|
system("git branch -D #{branch}")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment