Skip to content

Instantly share code, notes, and snippets.

@sgrimm
Created October 13, 2021 18:53
Show Gist options
  • Save sgrimm/531b56c1e36b7ef8b9580f23df80ece2 to your computer and use it in GitHub Desktop.
Save sgrimm/531b56c1e36b7ef8b9580f23df80ece2 to your computer and use it in GitHub Desktop.
Script to remove local PR branches after the PRs have been squash merged
#!/bin/bash
#
# Removes local branches whose contents have already been merged into main.
#
set -eo pipefail
say() {
echo ===
echo === "$@"
echo ===
}
if git diff --exit-code --quiet; then
:
else
echo "Repo is dirty! Aborting to avoid screwing it up." 1>&2
exit 1
fi
TEMP_BRANCH=trim.$$
LOG=/tmp/trim.$$.out
say "Updating main"
git checkout main
git pull --rebase -p
missing_remotes=$(git branch -vv | cut -c3- | awk '/: gone]/ { print $1 }')
for branch in $missing_remotes; do
say "Trying to trim $branch"
git checkout -f -B $TEMP_BRANCH "$branch"
git reset --soft $(git merge-base HEAD main)
git commit -a -m 'Dummy commit to check for squash merge'
if git rebase main > /dev/null 2> /dev/null; then
if git diff --quiet main; then
say "$branch is fully merged; deleting it"
git branch -D "$branch"
else
say "$branch is not fully merged"
fi
else
say "!!!!!! Failed to rebase $branch on main !!!!!!"
git rebase --abort
fi
done
git checkout main
git branch -D "$TEMP_BRANCH"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment