-
Notifications
You must be signed in to change notification settings - Fork 13.2k
60 lines (51 loc) · 2.09 KB
/
delete-closed-pr-branches.yml
File metadata and controls
60 lines (51 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Fires immediately when a PR is closed without merging and deletes the head
# branch — provided it lives on this repo (not a fork) and is not protected.
# Merged PRs are excluded because the repo's "automatically delete head branches"
# setting already handles those.
#
# Fork branches are skipped at the job level via the `if:` condition because
# we don't own them and the API would return a 403.
#
# To test without deleting anything, trigger this workflow manually via
# workflow_dispatch and supply a branch name. Manual runs always dry-run
# — they log "Would delete: <branch>" without touching anything.
name: Delete closed PR branches
on:
pull_request:
types: [closed]
workflow_dispatch:
inputs:
branch:
description: "Branch name to dry-run against"
required: true
type: string
permissions:
contents: write
jobs:
delete-branch:
if: github.event_name == 'workflow_dispatch' || (github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.merged == false)
runs-on: ubuntu-latest
steps:
- name: Delete branch associated with closed PR
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && 'true' || 'false' }}
run: |
branch="${{ github.event_name == 'workflow_dispatch' && inputs.branch || github.event.pull_request.head.ref }}"
if [ "$DRY_RUN" = "true" ]; then
echo "*** DRY RUN — no branches will be deleted ***"
fi
protected=$(gh api "repos/$GITHUB_REPOSITORY/branches?protected=true&per_page=100" \
| jq -r '.[].name')
if echo "$protected" | grep -qx "$branch"; then
echo "Skipped (protected): $branch"
exit 0
fi
if [ "$DRY_RUN" = "true" ]; then
echo "Would delete: $branch"
exit 0
fi
gh api "repos/$GITHUB_REPOSITORY/git/refs/heads/$branch" \
-X DELETE 2>/dev/null \
&& echo "Deleted: $branch" \
|| echo "Skipped (already gone): $branch"