Skip to content

Auto Delete Merged Branches #102

Auto Delete Merged Branches

Auto Delete Merged Branches #102

name: Auto Delete Merged Branches
on:
pull_request:
types: [closed] # Triggers when a PR is closed
schedule:
- cron: '0 0 * * 0' # Runs weekly on Sundays at midnight UTC
workflow_dispatch: # Allows manual triggering
permissions:
contents: write # Required to delete branches
pull-requests: read # Required to check PR status
jobs:
delete-merged-branches:
runs-on: ubuntu-latest
name: Delete Merged Branches
steps:
- name: Checkout Repository
uses: actions/checkout@v3
with:
fetch-depth: 0 # Fetch all branches and history
- name: Delete Merged Branches with GitHub CLI
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set +e # Don't exit on error
# Protected branches that should never be deleted
PROTECTED_BRANCHES=("main" "saas" "cli-tool")
echo "🔍 Finding merged branches..."
# Get all remote branches
git fetch --all --prune
# Get the default branch
DEFAULT_BRANCH=$(git remote show origin | grep 'HEAD branch' | cut -d' ' -f5)
echo "Default branch: $DEFAULT_BRANCH"
DELETED_COUNT=0
SKIPPED_COUNT=0
# Loop through all remote branches
for branch in $(git branch -r | grep -v '\->' | sed 's/origin\///'); do
# Skip protected branches
SKIP=false
for protected in "${PROTECTED_BRANCHES[@]}"; do
if [ "$branch" = "$protected" ]; then
SKIP=true
break
fi
done
if [ "$SKIP" = true ]; then
echo "⏭️ Skipping protected branch: $branch"
SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
continue
fi
# Check if branch is merged into default branch
MERGE_BASE=$(git merge-base $DEFAULT_BRANCH origin/$branch 2>/dev/null || echo "")
BRANCH_COMMIT=$(git rev-parse origin/$branch 2>/dev/null || echo "")
if [ -n "$MERGE_BASE" ] && [ -n "$BRANCH_COMMIT" ] && [ "$MERGE_BASE" = "$BRANCH_COMMIT" ]; then
echo "🗑️ Deleting merged branch: $branch"
if git push origin --delete "$branch" 2>&1; then
DELETED_COUNT=$((DELETED_COUNT + 1))
else
echo "⚠️ Failed to delete $branch"
SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
fi
else
echo "⏭️ Skipping unmerged branch: $branch"
SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
fi
done
echo ""
echo "✅ Cleanup complete!"
echo " - Deleted: $DELETED_COUNT branches"
echo " - Skipped: $SKIPPED_COUNT branches"
exit 0