|
| 1 | +name: Auto-Merge CI-Passing PRs |
| 2 | + |
| 3 | +on: |
| 4 | + pull_request_target: |
| 5 | + types: [opened, synchronize, reopened] |
| 6 | + |
| 7 | +permissions: |
| 8 | + contents: write |
| 9 | + pull-requests: write |
| 10 | + |
| 11 | +jobs: |
| 12 | + auto-merge: |
| 13 | + runs-on: ubuntu-latest |
| 14 | + steps: |
| 15 | + - name: Enable auto-merge for PRs |
| 16 | + uses: actions/github-script@v7 |
| 17 | + with: |
| 18 | + script: | |
| 19 | + const pr = context.payload.pull_request; |
| 20 | +
|
| 21 | + // Don't auto-merge draft PRs |
| 22 | + if (pr.draft) { |
| 23 | + console.log('PR is draft, skipping auto-merge'); |
| 24 | + return; |
| 25 | + } |
| 26 | +
|
| 27 | + // Don't auto-merge if PR is from the owner (manual merges for maintainers) |
| 28 | + if (pr.user.login === context.repo.owner) { |
| 29 | + console.log('PR is from repo owner, skipping auto-merge'); |
| 30 | + return; |
| 31 | + } |
| 32 | +
|
| 33 | + try { |
| 34 | + await github.rest.pulls.merge({ |
| 35 | + owner: context.repo.owner, |
| 36 | + repo: context.repo.repo, |
| 37 | + pull_number: pr.number, |
| 38 | + merge_method: 'squash' |
| 39 | + }); |
| 40 | + console.log(`PR #${pr.number} merged successfully`); |
| 41 | + } catch (error) { |
| 42 | + // If merge fails (conflicts, checks not passing), enable auto-merge |
| 43 | + if (error.status === 405 || error.status === 422) { |
| 44 | + try { |
| 45 | + await github.graphql(` |
| 46 | + mutation ($id: ID!, $method: PullRequestMergeMethod!) { |
| 47 | + enablePullRequestAutoMerge(input: { pullRequestId: $id, mergeMethod: $method }) { |
| 48 | + pullRequest { number } |
| 49 | + } |
| 50 | + } |
| 51 | + `, { |
| 52 | + id: pr.node_id, |
| 53 | + method: 'SQUASH' |
| 54 | + }); |
| 55 | + console.log(`Auto-merge enabled for PR #${pr.number}`); |
| 56 | + } catch (graphqlError) { |
| 57 | + console.log(`Could not enable auto-merge: ${graphqlError.message}`); |
| 58 | + } |
| 59 | + } else { |
| 60 | + console.log(`Unexpected error: ${error.message}`); |
| 61 | + } |
| 62 | + } |
0 commit comments