Skip to content

Instantly share code, notes, and snippets.

@jannismain
Forked from robmiller/git-cleanup-repo
Last active July 20, 2022 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jannismain/040451732b080b7f8ad85b463d278d73 to your computer and use it in GitHub Desktop.
Save jannismain/040451732b080b7f8ad85b463d278d73 to your computer and use it in GitHub Desktop.
A script for cleaning up Git repositories; it deletes branches that are fully merged into your default branch, prunes obsolete remote tracking branches, and as an added bonus will replicate these changes on the remote.
#!/bin/bash
# git-cleanup-repo
#
# Adapted by Jannis Mainczyk <jmainczyk@gmail.com>
# - support different default branches
# - add output per step
# Adapted by Rob Miller <rob@bigfish.co.uk>
# Original by Yorick Sijsling
default_branch=${1:-master}
read -p "Continue with default branch '${default_branch}' (y/N)? "
if [ "$REPLY" != "y" ]; then
exit
fi
echo "Checking out ${default_branch}..."
git checkout $default_branch &> /dev/null
# Make sure we're working with the most up-to-date version of master.
echo "Fetching changes..."
git fetch
# Prune obsolete remote tracking branches. These are branches that we
# once tracked, but have since been deleted on the remote.
echo "Prune obsolete remote tracking branches..."
git remote prune origin
# List all the branches that have been merged fully into master, and
# then delete them. We use the remote master here, just in case our
# local master is out of date.
echo "Delete fully merged local branches..."
git branch --merged origin/$default_branch | grep -v "${default_branch}$" | xargs git branch -d
echo "Delete fully merged remote branches..."
# Now the same, but including remote branches.
MERGED_ON_REMOTE=`git branch -r --merged origin/$default_branch | sed 's/ *origin\///' | grep -v 'master$'`
if [ "$MERGED_ON_REMOTE" ]; then
echo "The following remote branches are fully merged and will be removed:"
echo $MERGED_ON_REMOTE
read -p "Continue (y/N)? "
if [ "$REPLY" == "y" ]; then
git branch -r --merged origin/$default_branch | sed 's/ *origin\///' \
| grep -v "${default_branch}$" | xargs -I% git push origin :% 2>&1 \
| grep --colour=never 'deleted'
echo "Done!"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment