Commit 259314537a

259314537a6d27943296bb6d11ce208c6a3ad09c

parent: 3baabcafe5

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-02-27 23:12 UTC

Update existing comment once user fixes issues

Layout: unified · split

.github/workflows/pr-comment.yml +62 −22
@@ -7,6 +7,7 @@ on:
77
88permissions:
99 actions: read
10 contents: read
1011 pull-requests: write
1112
1213jobs:
@@ -16,6 +17,8 @@ jobs:
1617 if: github.event.workflow_run.event == 'pull_request'
1718
1819 steps:
20 - uses: actions/checkout@v4
21
1922 - name: Download PR metadata
2023 id: download
2124 continue-on-error: true
@@ -26,20 +29,13 @@ jobs:
2629 run-id: ${{ github.event.workflow_run.id }}
2730 github-token: ${{ secrets.GITHUB_TOKEN }}
2831
29 - name: Post comment
32 - name: Resolve PR context
33 id: context
3034 uses: actions/github-script@v7
3135 with:
3236 github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
3337 script: |
3438 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 }
4339
4440 // Determine the PR number
4541 let prNumber;
@@ -48,8 +44,6 @@ jobs:
4844 prNumber = parseInt(fs.readFileSync(numberFile, 'utf8').trim());
4945 }
5046 if (!prNumber) {
51 // workflow_run.pull_requests is empty for fork PRs, so
52 // fall back to searching by head SHA if needed
5347 const prs = context.payload.workflow_run.pull_requests;
5448 if (prs && prs.length > 0) {
5549 prNumber = prs[0].number;
@@ -72,23 +66,69 @@ jobs:
7266 }
7367 }
7468
75 // Skip if we already commented on this PR
69 // Fetch existing bot comment (if any) and write to file for Python
70 const marker = '<!-- pr-check-bot -->';
7671 const { data: comments } = await github.rest.issues.listComments({
7772 owner: context.repo.owner,
7873 repo: context.repo.repo,
7974 issue_number: prNumber,
8075 per_page: 100,
8176 });
82 if (comments.some(c => c.body.includes(marker))) {
83 console.log('Bot comment already exists — skipping.');
77 const existing = comments.find(c => c.body.includes(marker));
78 if (existing) {
79 fs.mkdirSync('pr-meta', { recursive: true });
80 fs.writeFileSync('pr-meta/existing-comment.md', existing.body);
81 fs.writeFileSync('pr-meta/existing-comment-id.txt', String(existing.id));
82 }
83
84 core.setOutput('pr_number', prNumber);
85
86 - name: Prepare comment
87 if: steps.context.outputs.pr_number
88 env:
89 CHECK_RUN_ID: ${{ github.event.workflow_run.id }}
90 GITHUB_REPOSITORY: ${{ github.repository }}
91 run: python lib/checks/prepare-comment.py
92
93 - name: Post or update comment
94 if: steps.context.outputs.pr_number
95 uses: actions/github-script@v7
96 with:
97 github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
98 script: |
99 const fs = require('fs');
100 const actionFile = 'pr-meta/action.txt';
101 if (!fs.existsSync(actionFile)) return;
102
103 const action = fs.readFileSync(actionFile, 'utf8').trim();
104 if (action === 'skip') {
105 console.log('Nothing to do — skipping.');
84106 return;
85107 }
86108
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 });
109 const bodyFile = 'pr-meta/final-comment.md';
110 if (!fs.existsSync(bodyFile)) {
111 console.log('No comment body found — skipping.');
112 return;
113 }
114 const body = fs.readFileSync(bodyFile, 'utf8').trim();
115 const prNumber = parseInt('${{ steps.context.outputs.pr_number }}');
116
117 if (action === 'create') {
118 await github.rest.issues.createComment({
119 owner: context.repo.owner,
120 repo: context.repo.repo,
121 issue_number: prNumber,
122 body,
123 });
124 console.log('Created bot comment.');
125 } else if (action === 'update') {
126 const commentId = parseInt(fs.readFileSync('pr-meta/existing-comment-id.txt', 'utf8').trim());
127 await github.rest.issues.updateComment({
128 owner: context.repo.owner,
129 repo: context.repo.repo,
130 comment_id: commentId,
131 body,
132 });
133 console.log('Updated bot comment.');
134 }
lib/checks/format-comment.py +2
@@ -108,6 +108,8 @@ def main():
108108 f.write(run_id)
109109
110110 findings = collect_findings()
111 with open(os.path.join(OUTPUT_DIR, "findings-count.txt"), "w") as f:
112 f.write(str(len(findings)))
111113 changes_summary = load_diff_summary()
112114 write_step_summary(findings)
113115
lib/checks/prepare-comment.py added +143
@@ -0,0 +1,143 @@
1"""Decides whether to create, update, or skip the PR bot comment.
2
3Reads:
4 pr-meta/comment.md — new comment from format-comment.py
5 pr-meta/findings-count.txt — number of findings (from format-comment.py)
6 pr-meta/existing-comment.md — current bot comment on the PR (from workflow)
7
8Writes:
9 pr-meta/action.txt — "create", "update", or "skip"
10 pr-meta/final-comment.md — the body to post or update with
11"""
12
13import os
14import re
15
16WORK_DIR = "pr-meta"
17
18
19def read_file(path):
20 """Read a file and return its stripped content, or None if missing/empty."""
21 try:
22 with open(path) as f:
23 content = f.read().strip()
24 return content if content else None
25 except Exception:
26 return None
27
28
29def read_findings_count(new_body):
30 """Return the findings count from findings-count.txt, or by counting bullets."""
31 raw = read_file(os.path.join(WORK_DIR, "findings-count.txt"))
32 if raw is not None:
33 try:
34 return int(raw)
35 except ValueError:
36 pass
37 # Fallback: count bullet lines before <details> (diff summary has its own bullets)
38 body_before_details = new_body.split("<details>")[0]
39 return len(re.findall(r"^- .+$", body_before_details, re.MULTILINE))
40
41
42def _was_already_passing(existing_body):
43 """Check if the most recent state in the comment is already all-clear."""
44 # If there's a previous "all passing" edit, the last state was passing
45 if re.search(r"^Edit(?: \d+)?: All checks are (now passing|passing now)", existing_body, re.MULTILINE):
46 return True
47 # If there are no edits at all, check the original comment body
48 if not re.search(r"^Edit(?: \d+)?:", existing_body, re.MULTILINE):
49 return "All our automated checks have passed" in existing_body
50 return False
51
52
53def _previous_failing_count(existing_body):
54 """Extract the findings count from the most recent state in the comment."""
55 # Check edit lines first (most recent state)
56 matches = re.findall(r"^Edit(?: \d+)?: (\d+) checks? (?:is|are) still failing", existing_body, re.MULTILINE)
57 if matches:
58 return int(matches[-1])
59 # No edits — count bullets in the original comment (before <details>)
60 if not re.search(r"^Edit(?: \d+)?:", existing_body, re.MULTILINE):
61 body_before_details = existing_body.split("<details>")[0]
62 bullets = re.findall(r"^- .+$", body_before_details, re.MULTILINE)
63 return len(bullets) if bullets else None
64 return None
65
66
67def build_edit_line(existing_body, findings_count, check_run_id, repo):
68 """Build the edit line to append, or None if nothing to do."""
69 run_tag = f"<!-- run:{check_run_id} -->"
70
71 # Idempotency: this run was already processed
72 if run_tag in existing_body:
73 return None
74
75 # Skip if the state hasn't changed
76 if findings_count == 0 and _was_already_passing(existing_body):
77 return None
78 if findings_count > 0 and _previous_failing_count(existing_body) == findings_count:
79 return None
80
81 # Count previous edits to determine the next number
82 edits = re.findall(r"^Edit(?: \d+)?:", existing_body, re.MULTILINE)
83 edit_count = len(edits)
84 next_edit = edit_count + 1
85
86 run_url = f"https://github.com/{repo}/actions/runs/{check_run_id}"
87
88 if findings_count == 0:
89 if edit_count == 0:
90 return f"Edit: All checks are now passing \U0001f389 {run_tag}"
91 return f"Edit {next_edit}: All checks are passing now \u2705 {run_tag}"
92
93 verb = "check is" if findings_count == 1 else "checks are"
94 return (
95 f"Edit {next_edit}: {findings_count} {verb} still failing, "
96 f"see [here]({run_url}) for details {run_tag}"
97 )
98
99
100def write_output(action, body=""):
101 """Write action.txt and (optionally) final-comment.md."""
102 os.makedirs(WORK_DIR, exist_ok=True)
103 with open(os.path.join(WORK_DIR, "action.txt"), "w") as f:
104 f.write(action)
105 if body:
106 with open(os.path.join(WORK_DIR, "final-comment.md"), "w") as f:
107 f.write(body)
108
109
110def main():
111 check_run_id = os.environ.get("CHECK_RUN_ID", "")
112 repo = os.environ.get("GITHUB_REPOSITORY", "")
113
114 new_body = read_file(os.path.join(WORK_DIR, "comment.md"))
115 if not new_body:
116 write_output("skip")
117 return
118
119 existing_body = read_file(os.path.join(WORK_DIR, "existing-comment.md"))
120
121 # No existing comment — create a new one
122 if not existing_body:
123 write_output("create", new_body)
124 return
125
126 # Existing comment — build an edit line to append
127 if not check_run_id:
128 write_output("skip")
129 return
130
131 findings_count = read_findings_count(new_body)
132 edit_line = build_edit_line(existing_body, findings_count, check_run_id, repo)
133
134 if not edit_line:
135 write_output("skip")
136 return
137
138 updated = existing_body.rstrip() + "\n\n" + edit_line
139 write_output("update", updated)
140
141
142if __name__ == "__main__":
143 main()