Skip to content

Instantly share code, notes, and snippets.

@lacostenycoder
Last active June 24, 2021 14:05
Show Gist options
  • Save lacostenycoder/730577210d08c2d9d38778b6f088d281 to your computer and use it in GitHub Desktop.
Save lacostenycoder/730577210d08c2d9d38778b6f088d281 to your computer and use it in GitHub Desktop.
add a shell alias to help auto-delete squashed branches - depends on git-flow with issue number in branch name

Gitflow local branch cleanup

This script relies on the git-flow branch naming best practices of including the issue number in the branch name. If you adhere to that, this script should work fine in most cases.

Dependency

This script relies on using the github cli tool

#!/usr/bin/env ruby
unless !!`which gh | grep 'bin/gh'`
abort('Please install github-cli tool from https://github.com/cli/cli#installation first. exiting now.')
end
issue_numbers = `gh issue list -s open -L 500 | grep -o '^[[:digit:]]*'`.split("\n")
branches = `git branch --sort=committerdate`.split("\n").map(&:strip)
branch_issue_numbers = branches.select{|b| b[/\/\d+/]}.map{|i| i[/\d+/]}
delete_issue_numbers = branch_issue_numbers.reject{|n| issue_numbers.include? n}.map(&:to_s)
unless delete_issue_numbers.any?
abort('No branches with matching open issues found')
end
regex = Regexp.new(delete_issue_numbers.join('|').insert(0, '/'))
branches_to_delete = branches.select{|b| b[regex]}
puts branches_to_delete
puts "\n"
puts 'These branches have issues which have been closed'
puts 'Are you sure you want to delete them? Y/N'
if gets.chomp.downcase == 'y'
branches_to_delete.each{|branch| `git branch -D #{branch}`}
puts 'The branches have been deleted'
else
abort('No branches have been deleted')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment