1

I'm working on improving team processes around merging and consolidating changes and would like to use Pull Requests in GitHub as a way to better manage changes.

My one concern about this is that I want to ensure that after merging a pull request, that the branch that has been merged is removed (I want the commits to stay, but I don't want our repository to be filled with a lot of stale branches that are no longer needed).

What's the best / safest way to accomplish this (preferably with the minimum number of steps, because with more steps there's more chance of one being forgotten).

Adam Luchjenbroers
  • 4,544
  • 2
  • 25
  • 34
  • 1
    Once you've merged the branch, click the "Remove branch" button that Github displays? And if someone forgets, simply delete the branch later? Nothing bad will happen if an unused branch still exists. You shouldn't worry too much about that. – JB Nizet Apr 26 '19 at 07:05
  • Does this answer your question? [How can I delete all Git branches which have been merged?](https://stackoverflow.com/questions/6127328/how-can-i-delete-all-git-branches-which-have-been-merged) – Michael Freidgeim Dec 25 '20 at 02:43

1 Answers1

2

Usually when I merge my feature branch into master after a successful code review I run:

git branch -d <branch-name>
git push origin :<branch-name>

Note: don't forget the : before the branch name when you push.

The first command deletes your branch locally and the second one deletes the remote one.

If this becomes a common practice in the team, you'll reach your goal.

A way to automatise it is to use a post-merge git hook, where you check if the current branch is master, you take the branch-name from the commit message and you run the two commands I wrote above.

Create a file in your project folder

touch .git/hooks/post-merge

and add execution permissions to it

chmod +x .git/hooks/post-merge

then open it with a text editor and add this content:

#!/bin/sh

#---------------------------------
# Delete branch merged into master
#---------------------------------

# Define your master branch name
master="master"

currentBranch=$(git branch | grep \* | cut -d ' ' -f2)

if [ $currentBranch = $master ]; then
    branchToDelete=$(git rev-parse --abbrev-ref $(git show-ref | grep $(git rev-parse HEAD^2)| cut -d ' ' -f 2))
    if [ $branchToDelete != "" ]; then
        git branch -d $branchToDelete
        git push origin :$branchToDelete
    fi 
fi
exit 0
xyzale
  • 655
  • 8
  • 14