Skip to content

Instantly share code, notes, and snippets.

@xrstf
Created July 11, 2024 22:35
Show Gist options
  • Save xrstf/092c4ced19e6a77614907505d2230508 to your computer and use it in GitHub Desktop.
Save xrstf/092c4ced19e6a77614907505d2230508 to your computer and use it in GitHub Desktop.
git smart pruner
#!/usr/bin/env bash
# Use this when Github bugs out and refuses to delete your
# head branches after a PR got merged, even though you
# have enabled that behaviour in your fork.
set -euo pipefail
source $(dirname "$0")/src/lib.sh
contains() {
grep "$1" >/dev/null 2>&1
}
# determine source repo
upstream=
origin=
if git remote | contains upstream; then
upstream=upstream
origin=origin
else
upstream=origin
origin=origin
fi
source="$(git remote get-url $upstream)"
num=25
echo "Finding the most recent $num merged PRs…"
mergedBranches="$(gh pr list --repo "$source" --author "@me" --limit $num --state merged --json headRefName | jq -r '.[].headRefName')"
echo "Listing branches in $origin"
myBranches="$(git ls-remote --heads "$origin")"
prune=false
for mergedBranch in $mergedBranches; do
if echo "$myBranches" | contains "refs/heads/$mergedBranch"; then
echo "Deleting remote branch $mergedBranch"
git push "$origin" --quiet --delete "$mergedBranch"
prune=true
fi
done
if $prune; then
git remote prune "$origin"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment