1+ name : Auto Delete Merged Branches
2+
3+ on :
4+ pull_request :
5+ types : [closed]
6+
7+ jobs :
8+ delete-merged-branch :
9+ runs-on : ubuntu-latest
10+ # Only run if PR was merged (not just closed)
11+ if : github.event.pull_request.merged == true
12+ permissions :
13+ contents : write
14+
15+ steps :
16+ - name : Checkout repository
17+ uses : actions/checkout@v4
18+
19+ - name : Delete merged branch
20+ env :
21+ GH_TOKEN : ${{ secrets.GITHUB_TOKEN }}
22+ run : |
23+ # Get the branch name that was merged
24+ BRANCH_NAME="${{ github.event.pull_request.head.ref }}"
25+
26+ # Skip deletion for protected branches
27+ PROTECTED_BRANCHES=("main" "master" "develop" "dev" "staging" "production")
28+
29+ echo "Checking if branch '$BRANCH_NAME' should be deleted..."
30+
31+ # Check if branch is in protected list
32+ for protected in "${PROTECTED_BRANCHES[@]}"; do
33+ if [[ "$BRANCH_NAME" == "$protected" ]]; then
34+ echo "Branch '$BRANCH_NAME' is protected, skipping deletion"
35+ exit 0
36+ fi
37+ done
38+
39+ # Check if it's a fork (external contributor)
40+ if [[ "${{ github.event.pull_request.head.repo.full_name }}" != "${{ github.repository }}" ]]; then
41+ echo "This is a fork PR, cannot delete external branch"
42+ exit 0
43+ fi
44+
45+ # Delete the branch using gh CLI
46+ echo "Deleting branch '$BRANCH_NAME'..."
47+ if gh api repos/${{ github.repository }}/git/refs/heads/$BRANCH_NAME --method DELETE; then
48+ echo "✅ Successfully deleted branch '$BRANCH_NAME'"
49+ else
50+ echo "❌ Failed to delete branch '$BRANCH_NAME' (may already be deleted or protected)"
51+ fi
0 commit comments