.github/workflows/pr-comment.yml
94 lines · 3165 bytes
1name: PR Comment
2
3on:
4 workflow_run:
5 workflows: ["PR Check"]
6 types: [completed]
7
8permissions:
9 actions: read
10 pull-requests: write
11
12jobs:
13 comment:
14 name: Post PR comment
15 runs-on: ubuntu-latest
16 if: github.event.workflow_run.event == 'pull_request'
17
18 steps:
19 - name: Download PR metadata
20 id: download
21 continue-on-error: true
22 uses: actions/download-artifact@v4
23 with:
24 name: pr-meta
25 path: pr-meta
26 run-id: ${{ github.event.workflow_run.id }}
27 github-token: ${{ secrets.GITHUB_TOKEN }}
28
29 - name: Post comment
30 uses: actions/github-script@v7
31 with:
32 github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
33 script: |
34 const fs = require('fs');
35 const marker = '<!-- pr-check-bot -->';
36
37 // Check if there are findings to post
38 const commentFile = 'pr-meta/comment.md';
39 if (!fs.existsSync(commentFile)) {
40 console.log('No findings to post — skipping.');
41 return;
42 }
43
44 // Determine the PR number
45 let prNumber;
46 const numberFile = 'pr-meta/number.txt';
47 if (fs.existsSync(numberFile)) {
48 prNumber = parseInt(fs.readFileSync(numberFile, 'utf8').trim());
49 }
50 if (!prNumber) {
51 // workflow_run.pull_requests is empty for fork PRs, so
52 // fall back to searching by head SHA if needed
53 const prs = context.payload.workflow_run.pull_requests;
54 if (prs && prs.length > 0) {
55 prNumber = prs[0].number;
56 } else {
57 const headSha = context.payload.workflow_run.head_sha;
58 const { data: prList } = await github.rest.pulls.list({
59 owner: context.repo.owner,
60 repo: context.repo.repo,
61 state: 'open',
62 sort: 'updated',
63 direction: 'desc',
64 per_page: 100,
65 });
66 const match = prList.find(pr => pr.head.sha === headSha);
67 if (!match) {
68 console.log(`No open PR found for SHA ${headSha} — skipping.`);
69 return;
70 }
71 prNumber = match.number;
72 }
73 }
74
75 // Skip if we already commented on this PR
76 const { data: comments } = await github.rest.issues.listComments({
77 owner: context.repo.owner,
78 repo: context.repo.repo,
79 issue_number: prNumber,
80 per_page: 100,
81 });
82 if (comments.some(c => c.body.includes(marker))) {
83 console.log('Bot comment already exists — skipping.');
84 return;
85 }
86
87 // Post the comment
88 const body = fs.readFileSync(commentFile, 'utf8').trim();
89 await github.rest.issues.createComment({
90 owner: context.repo.owner,
91 repo: context.repo.repo,
92 issue_number: prNumber,
93 body,
94 });