Skip to content

Instantly share code, notes, and snippets.

@jjb
Last active September 23, 2024 23:59
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
require 'time'
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)
if last_commit_date < threshold
branches_to_delete[branch] = threshold
end
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 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