Git Basics: branch cleanup

通常我们的项目都是创建分支开发来做功能迭代,随着项目的开发周期延长功能的不断迭代,git 远程库里会出现大量的分支。
理想状态下,当我们开发完一个功能后提交测试的时候,在处理 Merge Request 时,git merge 业务分支,同时勾选删除源开发分支 Delete source-branch,这样可以防止过多无用的 git 分支。这里记录一下如何手动清理分支:

Delete a branch both locally and remotely

To remove a local branch from your machine:

git branch -d <branch_name>

NOTE: If using -d (lowercase d), the branch will only be deleted if it has been merged. To force the delete to happen, you will need to use -D (uppercase D).

To remove a remote branch:

git push origin :<branch_name>

Thought : wasn’t a good indicator for [delete], As of Git 1.7.0, use this alternative syntax to delete remote branches:

git push origin --delete <branch_name>

[Tips]: if you want to complete both these steps with a single command, you can make an alias for it by adding the below to your ~/.gitconfig:

[alias]
  rmbranch = "!f(){ git branch -d ${1} && git push origin --delete ${1}; };f"

Alternatively, you can add this to your global config from the command line using

git config --global alias.rmbranch '!f(){ git branch -d ${1} && git push origin --delete ${1}; };f'

Sync local refs with remote repository

git remote prune <upstream>

will remove any remote refs you have locally that have been removed from your remote.

Also can fetch and prune with git fetch -p | --prune or git remote update [upstream] -p

The -p argument prunes deleted upstream branches. Thus, if the foo branch is deleted in the origin repository, git remote update -p will automatically delete your origin/foo ref.

Cleanup branches already merged

To delete local branches which have already been merged into master:

git checkout dev
git fetch -p # sync remote to local, also cleanup branches that have already been deleted
git branch --merged master |grep -v "\* master" |xargs -n 1 git branch -d

Note: For above command, if omit the master branch argument, we will get local branches which have already been merged into the current HEAD.

Now we need remove all remote branches have already been merged into dev:

git branch -r --merged origin/dev |grep -v '\*\|master\|dev' |sed 's#\s*origin/##' |xargs -n 1 echo

Make sure these branches are expected, And then remove from remote by replacing the echo with git push origin --delete

Another syntax to cleanup:

git push origin $(git branch -r --merged origin/master | sed "s/origin\\//:/" | egrep -v "HEAD|master|dev")

Note: Please make sure you known what these command to do before you execute it.

Now we can easily write a bash script (or ruby, or whatever) that goes through (maybe as a cron job) and deletes merged branches.

Reference Links

http://stevenharman.net/git-clean-delete-already-merged-branches