Skip to content

Commit e30bafe

Browse files
author
Quang Tran Minh
committed
feat: add auto branch deletion GitHub Action
- Automatically deletes branches after PR merge - Protects main, master, develop, development branches - Protects release/* and hotfix/* branches - Only deletes branches from same repository (not forks) - Includes safety checks and error handling
1 parent 8822bdb commit e30bafe

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
name: Auto Delete Branch After PR Merge
2+
3+
on:
4+
pull_request:
5+
types: [closed]
6+
7+
jobs:
8+
delete-branch:
9+
# Only run if the PR was merged (not just closed)
10+
if: github.event.pull_request.merged == true
11+
runs-on: ubuntu-latest
12+
13+
steps:
14+
- name: Delete merged branch
15+
run: |
16+
BRANCH_NAME="${{ github.event.pull_request.head.ref }}"
17+
18+
# Safety check: Never delete protected branches
19+
if [[ "$BRANCH_NAME" == "main" ]] || \
20+
[[ "$BRANCH_NAME" == "master" ]] || \
21+
[[ "$BRANCH_NAME" == "develop" ]] || \
22+
[[ "$BRANCH_NAME" == "development" ]] || \
23+
[[ "$BRANCH_NAME" =~ ^release/.* ]] || \
24+
[[ "$BRANCH_NAME" =~ ^hotfix/.* ]]; then
25+
echo "🔒 Skipping deletion of protected branch: $BRANCH_NAME"
26+
exit 0
27+
fi
28+
29+
# Only delete if it's from the same repository (not a fork)
30+
if [[ "${{ github.event.pull_request.head.repo.full_name }}" == "${{ github.event.pull_request.base.repo.full_name }}" ]]; then
31+
echo "🗑️ Deleting branch: $BRANCH_NAME"
32+
gh api repos/${{ github.repository }}/git/refs/heads/$BRANCH_NAME -X DELETE
33+
else
34+
echo "🔀 Skipping deletion of fork branch: $BRANCH_NAME"
35+
fi
36+
env:
37+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

0 commit comments

Comments
 (0)