Skip to content

Instantly share code, notes, and snippets.

@lacostenycoder
Last active March 10, 2020 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lacostenycoder/cab1f7d10fb36ebc98575bbc36151185 to your computer and use it in GitHub Desktop.
Save lacostenycoder/cab1f7d10fb36ebc98575bbc36151185 to your computer and use it in GitHub Desktop.
Clean branches by closed issue numbers
#!/usr/bin/env ruby
unless !!`which gh | grep 'bin/gh'`
abort('Please run brew install github/gh/gh first. exiting now.')
end
Dir.chdir(ENV['HOME'] + '/dev/clients/thoroughcare')
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
@lacostenycoder
Copy link
Author

lacostenycoder commented Aug 20, 2019

This script assumes you use specific git-flow type naming convention for your git branches where the issue number is included after a / so anything like bugfix/1234-fix-the-bug where 1234 is the actual issue number.

To use this script you'll need to gem install octokit as well as gem install netrc. Do this from your home path or wherever you have your system default ruby version set.

Then add your credentials to your ~/.netrc file see https://github.com/octokit/octokit.rb#using-a-netrc-file
Then you'll just need to modify line 3 of script to the path of your local repo.

To make it easy to run this script, save the file wherever you keep your custom ruby scripts.
Then add a symlink for example: ln -s ~/dev/ruby/clean_branches /usr/local/bin/clean_branches
Make the script executable for example: chmod +x ~/dev/ruby/clean_branches

Now you can just run clean_branches at anytime.

@lacostenycoder
Copy link
Author

Updated to use the new https://cli.github.com/ tool in place of octokit gem which seems to have some pagination issues atm.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment