Last active
August 29, 2015 13:56
-
-
Save micahbf/9010721 to your computer and use it in GitHub Desktop.
Prune local branches which have merged PRs on a GitHub repo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'octokit' | |
require 'git' | |
require 'optparse' | |
require 'io/console' | |
default_options = { | |
:owner => 'coupa', | |
:github_repo => 'coupa_development', | |
:local_repo_dir => Dir.pwd | |
} | |
options = {} | |
OptionParser.new do |opts| | |
opts.on("-u", "--user", "GitHub login") do |login| | |
options[:login] = user | |
end | |
opts.on("-o", "--owner", "Github repo owner") do |owner| | |
options[:owner] = owner | |
end | |
opts.on("-r", "--repo", "GitHub repository") do |repo| | |
options[:github_repo] = repo | |
end | |
opts.on("-l", "--local-repo", "Local repository") do |local| | |
options[:local_repo_dir] = local | |
end | |
end.parse! | |
options = default_options.merge(options) | |
if options[:login] | |
login = options[:login] | |
else | |
puts "Github login:" | |
login = gets.chomp | |
end | |
puts "Github password:" | |
password = STDIN.noecho(&:gets).chomp | |
puts "Comparing local branches against GitHub pull requests. This may take a moment..." | |
Octokit.configure do |c| | |
c.login = login | |
c.password = password | |
end | |
local_repo = Git.open(options[:local_repo_dir]) | |
to_delete = [] | |
local_repo.branches.local.each do |branch| | |
local_sha = branch.gcommit.sha | |
open_prs = Octokit.get("/repos/#{options[:owner]}/#{options[:github_repo]}/pulls", | |
{:head => "#{options[:owner]}:#{branch.name}", | |
:state => "open"}) | |
closed_prs = Octokit.get("/repos/#{options[:owner]}/#{options[:github_repo]}/pulls", | |
{:head => "#{options[:owner]}:#{branch.name}", | |
:state => "closed"}) | |
if open_prs.empty? && !closed_prs.empty? && closed_prs.all? { |pr| pr.merged_at && pr.head.sha == local_sha } | |
to_delete << branch | |
end | |
end | |
puts "The following branches have no open PRs and at least one merged PR. Do you want to delete them?" | |
to_delete.each { |b| puts b.name } | |
puts "Delete these local branches? (y/n)" | |
exit unless gets.chomp == "y" | |
to_delete.each { |b| b.delete } | |
puts "Branches deleted." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment