|
| 1 | +name: Auto Close Empty PRs |
| 2 | + |
| 3 | +on: |
| 4 | + pull_request: |
| 5 | + types: |
| 6 | + - opened |
| 7 | + |
| 8 | +jobs: |
| 9 | + check-and-close: |
| 10 | + runs-on: ubuntu-latest |
| 11 | + permissions: |
| 12 | + pull-requests: write |
| 13 | + issues: write |
| 14 | + |
| 15 | + steps: |
| 16 | + - name: Check PR for changes |
| 17 | + id: check_changes |
| 18 | + uses: actions/github-script@v7 |
| 19 | + with: |
| 20 | + script: | |
| 21 | + const { data: files } = await github.rest.pulls.listFiles({ |
| 22 | + owner: context.repo.owner, |
| 23 | + repo: context.repo.repo, |
| 24 | + pull_number: context.issue.number |
| 25 | + }); |
| 26 | +
|
| 27 | + // Check if there are any files changed |
| 28 | + const hasChanges = files.length > 0; |
| 29 | +
|
| 30 | + // Also check if all changes are 0 (sometimes PRs show files but with 0 changes) |
| 31 | + const hasActualChanges = files.some(file => |
| 32 | + file.additions > 0 || file.deletions > 0 || file.changes > 0 |
| 33 | + ); |
| 34 | +
|
| 35 | + console.log(`Files changed: ${files.length}`); |
| 36 | + console.log(`Has actual changes: ${hasActualChanges}`); |
| 37 | +
|
| 38 | + return { hasChanges: hasChanges && hasActualChanges }; |
| 39 | +
|
| 40 | + - name: Close PR if empty |
| 41 | + if: steps.check_changes.outputs.result == 'false' || fromJSON(steps.check_changes.outputs.result).hasChanges == false |
| 42 | + uses: actions/github-script@v7 |
| 43 | + with: |
| 44 | + script: | |
| 45 | + // Add a comment explaining why the PR is being closed |
| 46 | + await github.rest.issues.createComment({ |
| 47 | + owner: context.repo.owner, |
| 48 | + repo: context.repo.repo, |
| 49 | + issue_number: context.issue.number, |
| 50 | + body: '⚠️ This pull request appears to contain no changes and will be automatically closed.\n\nIf you believe this is an error, please add your changes and push them to the branch.' |
| 51 | + }); |
| 52 | +
|
| 53 | + // Close the pull request |
| 54 | + await github.rest.pulls.update({ |
| 55 | + owner: context.repo.owner, |
| 56 | + repo: context.repo.repo, |
| 57 | + pull_number: context.issue.number, |
| 58 | + state: 'closed' |
| 59 | + }); |
| 60 | +
|
| 61 | + // Add a label (optional) |
| 62 | + await github.rest.issues.addLabels({ |
| 63 | + owner: context.repo.owner, |
| 64 | + repo: context.repo.repo, |
| 65 | + issue_number: context.issue.number, |
| 66 | + labels: ['auto-closed', 'no-changes'] |
| 67 | + }); |
0 commit comments