|
| 1 | +name: Delete Merged Branch |
| 2 | + |
| 3 | +on: |
| 4 | + pull_request: |
| 5 | + types: [closed, labeled] |
| 6 | + |
| 7 | +jobs: |
| 8 | + delete-branch: |
| 9 | + runs-on: ubuntu-latest |
| 10 | + steps: |
| 11 | + - name: Delete branch |
| 12 | + uses: actions/github-script@v7 |
| 13 | + with: |
| 14 | + script: | |
| 15 | + const prNumber = context.payload.pull_request.number; |
| 16 | + const eventAction = context.payload.action; |
| 17 | +
|
| 18 | + // Fetch the current PR state to get the latest labels and status |
| 19 | + const { data: pr } = await github.rest.pulls.get({ |
| 20 | + owner: context.repo.owner, |
| 21 | + repo: context.repo.repo, |
| 22 | + pull_number: prNumber, |
| 23 | + }); |
| 24 | +
|
| 25 | + const branchName = pr.head.ref; |
| 26 | + const owner = context.repo.owner; |
| 27 | + const repo = context.repo.repo; |
| 28 | + const labels = pr.labels.map(l => l.name); |
| 29 | + const isClosed = pr.state === 'closed'; |
| 30 | + const isMerged = pr.merged; |
| 31 | + const hasMergedLabel = labels.some(l => l.toLowerCase() === 'merged'); |
| 32 | +
|
| 33 | + console.log(`Event: ${eventAction}`); |
| 34 | + console.log(`PR #${prNumber} state: ${pr.state}, merged: ${isMerged}`); |
| 35 | + console.log(`Labels: ${labels.join(', ') || '(none)'}`); |
| 36 | +
|
| 37 | + // Only proceed if PR is closed AND (merged via GitHub OR has "Merged" label) |
| 38 | + if (!isClosed) { |
| 39 | + console.log('Skipping: PR is not closed'); |
| 40 | + return; |
| 41 | + } |
| 42 | +
|
| 43 | + if (!isMerged && !hasMergedLabel) { |
| 44 | + console.log('Skipping: PR was closed without merging and has no "Merged" label'); |
| 45 | + return; |
| 46 | + } |
| 47 | +
|
| 48 | + // Skip if the branch is not in the same repository |
| 49 | + const headRepo = pr.head.repo; |
| 50 | + const baseRepoFullName = `${owner}/${repo}`; |
| 51 | + if (!headRepo || headRepo.full_name !== baseRepoFullName) { |
| 52 | + console.log(`Skipping: branch '${branchName}' is not in ${baseRepoFullName}`); |
| 53 | + return; |
| 54 | + } |
| 55 | +
|
| 56 | + // Skip protected branches |
| 57 | + const protectedBranches = ['main', 'master']; |
| 58 | + if (protectedBranches.includes(branchName)) { |
| 59 | + console.log(`Skipping: branch '${branchName}' is protected`); |
| 60 | + return; |
| 61 | + } |
| 62 | +
|
| 63 | + try { |
| 64 | + await github.rest.git.deleteRef({ |
| 65 | + owner, |
| 66 | + repo, |
| 67 | + ref: `heads/${branchName}`, |
| 68 | + }); |
| 69 | + console.log(`Successfully deleted branch '${branchName}'`); |
| 70 | + } catch (error) { |
| 71 | + if (error.status === 422) { |
| 72 | + console.log(`Branch '${branchName}' was already deleted`); |
| 73 | + } else { |
| 74 | + console.error(`Failed to delete branch '${branchName}': ${error.message}`); |
| 75 | + throw error; |
| 76 | + } |
| 77 | + } |
0 commit comments