#!/usr/bin/env ruby
current_branch = `git symbolic-ref --short HEAD`.chompif current_branch != "master"if $?.exitstatus == 0puts "WARNING: You are on branch #{current_branch}, NOT master."elseputs "WARNING: You are not on a branch"endputsend
puts "Fetching merged branches..."remote_branches= `git branch -r --merged`.split("\n").map(&:strip).reject {|b| b =~ /\/(#{current_branch}|master)/}
local_branches= `git branch --merged`.gsub(/^\* /, '').split("\n").map(&:strip).reject {|b| b =~ /(#{current_branch}|master)/}
if remote_branches.empty? && local_branches.empty?puts "No existing branches have been merged into #{current_branch}."elseputs "This will remove the following branches:"puts remote_branches.join("\n")puts local_branches.join("\n")puts "Proceed?"if gets =~ /^y/iremote_branches.each do |b|remote, branch = b.split(/\//)`git push #{remote} :#{branch}`end
# Remove local branches`git branch -d #{local_branches.join(' ')}`elseputs "No branches removed."endend
git config --global alias.cleanup '!COMMAND="git branch -D"; while [[ $# -gt 0 ]]; do case "$1" in -d|--dryrun) COMMAND="echo"; shift; ;; *) MAIN_BRANCH="$1"; shift;; esac; done; MAIN_BRANCH="${MAIN_BRANCH:-$(git symbolic-ref refs/remotes/origin/HEAD)}"; git for-each-ref --merged="$MAIN_BRANCH" --no-contains="$MAIN_BRANCH" --format="%(refname:short)" refs/heads/ | xargs -n1 -r $COMMAND;#'
用法:
git cleanup # delete all branches that have been merged into origin/HEADgit cleanup master2 # delete all branches that have been merged into master2git cleanup master2 -d # do a dryrun (show names of branches that would be delted)