Skip to content

Instantly share code, notes, and snippets.

@rpbaltazar
Created June 23, 2023 04:00
Show Gist options
  • Save rpbaltazar/2878977932e86c603d5010b37672c86a to your computer and use it in GitHub Desktop.
Save rpbaltazar/2878977932e86c603d5010b37672c86a to your computer and use it in GitHub Desktop.
Clean local branches that no longer have a linked remote
#!/usr/bin/env ruby
# frozen_string_literal: true
puts 'Getting list of remote branches'
remote_branches = `git ls-remote origin |\
grep 'refs/heads/' |\
cut -c53-`.split "\n"
local_branches = `git branch |\
tr -d ' *'`.split "\n"
local_only = local_branches.reject do |local|
remote_branches.include? local
end
puts 'The following branches are local_only:'
puts local_only
unless ARGV[0] == '-i'
puts <<WARNING_MESSAGE
:WARNING:
Are you sure you want to irrecoverably DESTROY all these branches?!!
if so enter YES and press <return>
NOTE: To destroy branches interactively use the -i option
WARNING_MESSAGE
if STDIN.gets.chomp != 'YES'
puts 'Aborting'
exit 1
end
end
local_only.each do |candidate_for_destuction|
if ARGV[0] == '-i'
puts candidate_for_destuction.to_s
puts 'Confirm delete (y/N/q)'
cfm = STDIN.gets.chomp.downcase
exit if cfm == 'q'
next unless cfm.chomp.downcase == 'y'
end
`git branch -D #{candidate_for_destuction}`
puts "Deleted: #{candidate_for_destuction}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment