Skip to content

Instantly share code, notes, and snippets.

@mikedidomizio
Last active May 27, 2022 20:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikedidomizio/ad76aa8e40cecad336f666e4b315fc6f to your computer and use it in GitHub Desktop.
Save mikedidomizio/ad76aa8e40cecad336f666e4b315fc6f to your computer and use it in GitHub Desktop.
Script to delete branches that are stale and have no commits
#!/usr/bin/env bash
# Proceeds to go through remote branches and delete any branch that is over a year old and does not have a commit ahead of master
# Proceeds to output what it will delete
# ./cleanup.sh ../project-directory
# Proceeds to output and delete
# ./cleanup.sh ../project-directory --real-run
(
cd $1 || exit
RED='\033[0;31m'
NC='\033[0m' # No Color
NUMBER_OF_PRUNED_BRANCHES=0
NUMBER_OF_SKIPPED_BRANCHES=0
CURRENT_UNIX_TIMESTAMP=$(date +%s)
DEFAULT_BRANCH=$(git remote show origin | sed -n '/HEAD branch/s/.*: //p')
if [[ $2 = '--real-run' ]];
then
echo "${RED}real run flag is activated, waiting 10 seconds before proceeding to delete${NC}"
sleep 10
fi;
for branch in `git branch -r | grep -v HEAD`;
do
# Although the default branch could be protected, and it could have recent commits, this might not be necessary
# We skip it anyways just in case
if [ "$branch" = "origin/${DEFAULT_BRANCH}" ];
then
echo "skipping default branch - $branch"
continue
fi
COMMITS_DIFF_FROM_MASTER=$(git rev-list --left-right --count master...$branch | awk -F' ' '{print $2}')
if [ "$COMMITS_DIFF_FROM_MASTER" = "0" ];
then
# we know the branch has no commits, therefore we can get the last commit (master) and check the date of that to get the age of the branch
LAST_COMMIT_DATE=$(git log -1 --format=%ct $branch)
NUMBER_OF_SECONDS_OLD_OF_BRANCH="$(($CURRENT_UNIX_TIMESTAMP-$LAST_COMMIT_DATE))"
# 31536000 is one year
if [[ $NUMBER_OF_SECONDS_OLD_OF_BRANCH -gt 31536000 ]];
then
echo "pruning $branch"
if [[ $2 = '--real-run' ]];
then
git push origin --delete ${branch:7}
fi;
NUMBER_OF_PRUNED_BRANCHES=$((NUMBER_OF_PRUNED_BRANCHES+1))
else
echo "branch skipped - $branch"
NUMBER_OF_SKIPPED_BRANCHES=$((NUMBER_OF_SKIPPED_BRANCHES+1))
fi
fi
done
echo "Number of pruned branches: $NUMBER_OF_PRUNED_BRANCHES"
echo "Number of skipped branches: $NUMBER_OF_SKIPPED_BRANCHES"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment