.github/workflows/pr-comment.yml

255 lines · 9446 bytes

  1name: PR Comment
  2
  3on:
  4  workflow_run:
  5    workflows: ["PR Check"]
  6    types: [completed]
  7  pull_request_review:
  8    types: [submitted]
  9
 10permissions:
 11  actions: read
 12  checks: read
 13  contents: read
 14  pull-requests: write
 15
 16jobs:
 17  comment:
 18    name: Post PR comment
 19    runs-on: ubuntu-latest
 20    if: github.event.workflow_run.event == 'pull_request'
 21
 22    steps:
 23      - uses: actions/checkout@v5
 24
 25      - name: Download PR metadata
 26        id: download
 27        continue-on-error: true
 28        uses: actions/download-artifact@v7
 29        with:
 30          name: pr-meta
 31          path: pr-meta
 32          run-id: ${{ github.event.workflow_run.id }}
 33          github-token: ${{ secrets.GITHUB_TOKEN }}
 34
 35      - name: Resolve PR context
 36        id: context
 37        uses: actions/github-script@v8
 38        with:
 39          github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
 40          script: |
 41            const fs = require('fs');
 42
 43            // Determine the PR number
 44            let prNumber;
 45            const numberFile = 'pr-meta/number.txt';
 46            if (fs.existsSync(numberFile)) {
 47              prNumber = parseInt(fs.readFileSync(numberFile, 'utf8').trim());
 48            }
 49            if (!prNumber) {
 50              const prs = context.payload.workflow_run.pull_requests;
 51              if (prs && prs.length > 0) {
 52                prNumber = prs[0].number;
 53              } else {
 54                const headSha = context.payload.workflow_run.head_sha;
 55                const { data: prList } = await github.rest.pulls.list({
 56                  owner: context.repo.owner,
 57                  repo: context.repo.repo,
 58                  state: 'open',
 59                  sort: 'updated',
 60                  direction: 'desc',
 61                  per_page: 100,
 62                });
 63                const match = prList.find(pr => pr.head.sha === headSha);
 64                if (!match) {
 65                  console.log(`No open PR found for SHA ${headSha} — skipping.`);
 66                  return;
 67                }
 68                prNumber = match.number;
 69              }
 70            }
 71
 72            // Fetch existing bot comment (if any) and write to file for Python
 73            const marker = '<!-- pr-check-bot -->';
 74            const { data: comments } = await github.rest.issues.listComments({
 75              owner: context.repo.owner,
 76              repo: context.repo.repo,
 77              issue_number: prNumber,
 78              per_page: 100,
 79            });
 80            const existing = comments.find(c => c.body.includes(marker));
 81            if (existing) {
 82              fs.mkdirSync('pr-meta', { recursive: true });
 83              fs.writeFileSync('pr-meta/existing-comment.md', existing.body);
 84              fs.writeFileSync('pr-meta/existing-comment-id.txt', String(existing.id));
 85            }
 86
 87            core.setOutput('pr_number', prNumber);
 88
 89      - name: Prepare comment
 90        if: steps.context.outputs.pr_number
 91        env:
 92          CHECK_RUN_ID: ${{ github.event.workflow_run.id }}
 93          GITHUB_REPOSITORY: ${{ github.repository }}
 94        run: python lib/checks/prepare-comment.py
 95
 96      - name: Post or update comment
 97        if: steps.context.outputs.pr_number
 98        uses: actions/github-script@v8
 99        with:
100          github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
101          script: |
102            const fs = require('fs');
103            const actionFile = 'pr-meta/action.txt';
104            if (!fs.existsSync(actionFile)) return;
105
106            const action = fs.readFileSync(actionFile, 'utf8').trim();
107            if (action === 'skip') {
108              console.log('Nothing to do — skipping.');
109              return;
110            }
111
112            const bodyFile = 'pr-meta/final-comment.md';
113            if (!fs.existsSync(bodyFile)) {
114              console.log('No comment body found — skipping.');
115              return;
116            }
117            const body = fs.readFileSync(bodyFile, 'utf8').trim();
118            const prNumber = parseInt('${{ steps.context.outputs.pr_number }}');
119
120            if (action === 'create') {
121              await github.rest.issues.createComment({
122                owner: context.repo.owner,
123                repo: context.repo.repo,
124                issue_number: prNumber,
125                body,
126              });
127              console.log('Created bot comment.');
128            } else if (action === 'update') {
129              const commentId = parseInt(fs.readFileSync('pr-meta/existing-comment-id.txt', 'utf8').trim());
130              await github.rest.issues.updateComment({
131                owner: context.repo.owner,
132                repo: context.repo.repo,
133                comment_id: commentId,
134                body,
135              });
136              console.log('Updated bot comment.');
137            }
138
139            // Auto-assign Lissy93 for review when appropriate (non-critical)
140            try {
141              const readInt = (f) => fs.existsSync(f) ? parseInt(fs.readFileSync(f, 'utf8').trim()) : NaN;
142              const errors = readInt('pr-meta/error-count.txt');
143              const total = readInt('pr-meta/findings-count.txt');
144              const shouldAssign =
145                (action === 'create' && errors === 0 && total === 0) ||
146                (action === 'update' && errors === 0);
147              if (shouldAssign) {
148                await github.rest.issues.addAssignees({
149                  owner: context.repo.owner,
150                  repo: context.repo.repo,
151                  issue_number: prNumber,
152                  assignees: ['Lissy93'],
153                });
154                console.log('Assigned Lissy93 for review.');
155              }
156            } catch (err) {
157              console.log(`Failed to auto-assign: ${err.message}`);
158            }
159
160  review-notify:
161    name: Notify maintainer
162    runs-on: ubuntu-latest
163    if: github.event_name == 'pull_request_review'
164
165    steps:
166      - uses: actions/checkout@v5
167
168      - name: Fetch review and CI context
169        id: context
170        uses: actions/github-script@v8
171        with:
172          github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
173          script: |
174            const fs = require('fs');
175            const pr = context.payload.pull_request;
176            const { owner, repo } = context.repo;
177
178            // Fetch reviews — extract user login and state
179            const { data: reviews } = await github.rest.pulls.listReviews({
180              owner, repo, pull_number: pr.number, per_page: 100,
181            });
182            const reviewData = reviews.map(r => ({
183              user: r.user.login,
184              state: r.state,
185            }));
186
187            // Fetch check runs for the PR head SHA
188            const { data: { check_runs } } = await github.rest.checks.listForRef({
189              owner, repo, ref: pr.head.sha, per_page: 100,
190            });
191            const checkData = check_runs.map(cr => ({
192              status: cr.status,
193              conclusion: cr.conclusion,
194            }));
195
196            // Check if we already posted the notification
197            const marker = '<!-- pr-review-ready -->';
198            const { data: comments } = await github.rest.issues.listComments({
199              owner, repo, issue_number: pr.number, per_page: 100,
200            });
201            const alreadyNotified = comments.some(c => c.body.includes(marker));
202
203            // Write data for Python
204            fs.mkdirSync('pr-meta', { recursive: true });
205            fs.writeFileSync('pr-meta/reviews.json', JSON.stringify(reviewData));
206            fs.writeFileSync('pr-meta/check-runs.json', JSON.stringify(checkData));
207            fs.writeFileSync('pr-meta/already-notified.txt', String(alreadyNotified));
208
209            core.setOutput('pr_number', pr.number);
210
211      - name: Check review readiness
212        run: python lib/checks/check-review-ready.py
213
214      - name: Post notification
215        uses: actions/github-script@v8
216        with:
217          github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
218          script: |
219            const fs = require('fs');
220            const actionFile = 'pr-meta/action.txt';
221            if (!fs.existsSync(actionFile)) return;
222
223            const action = fs.readFileSync(actionFile, 'utf8').trim();
224            if (action !== 'notify') {
225              console.log('Not ready for review — skipping.');
226              return;
227            }
228
229            const body = [
230              '<!-- pr-review-ready -->',
231              'This PR is now ready to be merged, pending maintainer review. All checks are passing and it has been peer-reviewed.',
232              '',
233              '@Lissy93 - Please evaluate, and either merge or leave feedback.',
234            ].join('\n');
235
236            const prNumber = parseInt('${{ steps.context.outputs.pr_number }}');
237
238            await github.rest.issues.createComment({
239              owner: context.repo.owner,
240              repo: context.repo.repo,
241              issue_number: prNumber,
242              body,
243            });
244
245            // Once all checks pass, assign the PR to myself, so i get notiifcation to review
246            try {
247              await github.rest.issues.addAssignees({
248                owner: context.repo.owner,
249                repo: context.repo.repo,
250                issue_number: prNumber,
251                assignees: ['Lissy93'],
252              });
253            } catch (err) {
254              console.log(`Failed to assign Lissy93: ${err.message}`);
255            }