|
| 1 | +name: Auto-close issues mentioned in merged PR |
| 2 | + |
| 3 | +on: |
| 4 | + pull_request_target: |
| 5 | + types: [closed] |
| 6 | + |
| 7 | +permissions: |
| 8 | + issues: write |
| 9 | + pull-requests: read |
| 10 | + |
| 11 | +jobs: |
| 12 | + auto-close-issues: |
| 13 | + runs-on: ubuntu-latest |
| 14 | + if: github.event.pull_request.merged == true |
| 15 | + |
| 16 | + steps: |
| 17 | + - name: Auto-close referenced issues |
| 18 | + uses: actions/github-script@v7 |
| 19 | + with: |
| 20 | + script: | |
| 21 | + const pr = context.payload.pull_request; |
| 22 | +
|
| 23 | + // Combine PR title and body |
| 24 | + const text = `${pr.title}\n${pr.body || ""}`; |
| 25 | +
|
| 26 | + // Match issue references like #12, #45 |
| 27 | + const issueNumbers = [...text.matchAll(/#(\d+)/g)] |
| 28 | + .map(match => match[1]); |
| 29 | +
|
| 30 | + if (issueNumbers.length === 0) { |
| 31 | + console.log("No referenced issues found."); |
| 32 | + return; |
| 33 | + } |
| 34 | +
|
| 35 | + for (const issueNumber of issueNumbers) { |
| 36 | + try { |
| 37 | + await github.rest.issues.update({ |
| 38 | + owner: context.repo.owner, |
| 39 | + repo: context.repo.repo, |
| 40 | + issue_number: issueNumber, |
| 41 | + state: "closed", |
| 42 | + }); |
| 43 | +
|
| 44 | + await github.rest.issues.createComment({ |
| 45 | + owner: context.repo.owner, |
| 46 | + repo: context.repo.repo, |
| 47 | + issue_number: issueNumber, |
| 48 | + body: `Closed automatically via merged PR #${pr.number}.`, |
| 49 | + }); |
| 50 | +
|
| 51 | + console.log(`Closed issue #${issueNumber}`); |
| 52 | + } catch (error) { |
| 53 | + console.log( |
| 54 | + `Failed to close issue #${issueNumber}: ${error.message}` |
| 55 | + ); |
| 56 | + } |
| 57 | + } |
0 commit comments