Skip to content

Instantly share code, notes, and snippets.

@mattknox
Created September 2, 2016 20:33
Show Gist options
  • Save mattknox/960a77cc7969eaa7c59468a2c59aa059 to your computer and use it in GitHub Desktop.
Save mattknox/960a77cc7969eaa7c59468a2c59aa059 to your computer and use it in GitHub Desktop.
cleanup merged branches
#! /usr/bin/env ruby
# if run inside a git repo, this will pull current master and force remove all branches that have no diff against master.
# this is useful if you use squash-merge- or rebase-based merge strategies, and does not require anything particular of the
# developer to use.
in_repo = system("git status")
unless in_repo
puts "run this from inside a git repo"
exit 1
end
git_status = `git status 2>&1`
if git_status.match(/Changes to be committed:/) || git_status.match(/Changes not staged for commit:/)
puts "stash or commit state first!"
exit 1
end
`git checkout master`
`git pull origin master`
branches = `git branch`.split.reject {|bn| ["master", "*"].member? bn }
branches.each do |bn|
`git checkout #{bn}`
merged = system("git merge origin/master -m 'merged by repo_cleaner'")
diff = nil
if merged
diff = `git diff origin/master`
else
reset = system("git reset --hard")
exit(1) unless reset
end
`git checkout master`
if diff == ""
`git branch -D #{bn}`
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment