Created
January 10, 2019 12:39
-
-
Save bymyslf/7f07180970b3a3bf4ee1907490905641 to your computer and use it in GitHub Desktop.
Git post-merge hook to delete merged branch
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
#!/bin/bash | |
# Based on: https://github.com/brianstorti/git-hooks/blob/master/hooks/post-merge | |
exec < /dev/tty | |
# Merge can go three ways: | |
# * F: fast forward: no commit is created, only a ref is changed | |
# * A: automatic: true merge (non-ff) without conflicts. A new commit is created | |
# * C: merge with conflicts: no commit is created but the index is prepared (partially) | |
# for a merge commit | |
# How it appears on reflog: | |
# eccb159 master@{0}: commit (merge): Merge branch 'qa' -> When there is a conflict (C) | |
# d021b0e master@{1}: merge qa: Merge made by recursive. -> Automatic (A) | |
# e1cde23 master@{2}: merge qa: Fast-forward -> Fast-forward (F) | |
# For cases F and A, the "post-merge" hook is called, but for case C, just the | |
# "post-commit" is called, so we need to do the verification there, too. | |
############################################################################### | |
# Warns if you try | |
# * to merge the "qa" branch on any other branch | |
# * to merge on master a branch that is not yet merged on qa | |
############################################################################### | |
branch_name=$(git branch | grep "*" | sed "s/\* //") | |
reflog_message=$(git reflog -1) | |
merged_branch_name=$(echo $reflog_message | cut -d" " -f 4 | sed "s/://") | |
# if the merge was caused by a "git pull", we can safely ignore it | |
if [[ $reflog_message =~ "pull" ]]; then | |
exit 0 | |
fi | |
if [[ $branch_name == "master" ]]; then | |
read -p "Branch successfully merged on master. Do you want to remove it, both locally and remotely? (y/N) " answer | |
if [[ "$answer" == "y" ]]; then | |
git branch -D $merged_branch_name | |
git remote | grep -q origin | |
if [[ $? == 0 ]]; then | |
git push origin --delete $merged_branch_name | |
fi | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment