lib/checks/prepare-comment.py
204 lines · 7649 bytes
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 _extract_pr_author(existing_body):
68 """Extract the PR author username from the 'Hello @user' greeting."""
69 match = re.search(r"Hello @([\w-]+)", existing_body)
70 return match.group(1) if match else None
71
72
73_SUBMISSION_INFO_RE = re.compile(
74 r"<details><summary>Submission Info</summary>\s*\n.*?</details>",
75 re.DOTALL,
76)
77
78
79def _extract_submission_info(body):
80 """Extract the Submission Info <details> block, or None if absent."""
81 match = _SUBMISSION_INFO_RE.search(body)
82 return match.group(0) if match else None
83
84
85def _refresh_submission_info(existing_body, new_body):
86 """Replace or insert the Submission Info block from new_body into existing_body."""
87 new_block = _extract_submission_info(new_body)
88 if not new_block:
89 return existing_body
90 old_block = _extract_submission_info(existing_body)
91 if old_block:
92 if old_block == new_block:
93 return existing_body
94 return existing_body.replace(old_block, new_block)
95 # No existing block — insert before Updates section or workflow run link
96 for anchor in ("---\n\n### Updates", "<sup>For full details"):
97 if anchor in existing_body:
98 return existing_body.replace(anchor, new_block + "\n\n" + anchor, 1)
99 return existing_body.rstrip() + "\n\n" + new_block
100
101
102def build_edit_line(existing_body, findings_count, check_run_id, repo):
103 """Build the edit line to append, or None if nothing to do."""
104 run_tag = f"<!-- run:{check_run_id} -->"
105
106 # Idempotency: this run was already processed
107 if run_tag in existing_body:
108 return None
109
110 # Skip if the state hasn't changed
111 if findings_count == 0 and _was_already_passing(existing_body):
112 return None
113 if findings_count > 0 and _previous_failing_count(existing_body) == findings_count:
114 return None
115
116 # Count previous edits to determine the next number
117 edits = re.findall(r"^(?:\*\*)?Edit(?: \d+)?(?:\*\*)?:", existing_body, re.MULTILINE)
118 edit_count = len(edits)
119 next_edit = edit_count + 1
120
121 run_url = f"https://github.com/{repo}/actions/runs/{check_run_id}"
122
123 # Build resolved-issue prefix
124 prev_count = _previous_failing_count(existing_body)
125 resolved_prefix = ""
126 if prev_count is not None and prev_count > findings_count:
127 resolved = prev_count - findings_count
128 noun = "issue was" if resolved == 1 else "issues were"
129 resolved_prefix = f"{resolved} {noun} resolved, but "
130
131 if findings_count == 0:
132 edit_label = "**Edit:**" if edit_count == 0 else f"**Edit {next_edit}:**"
133 line = f"{edit_label} - All checks are now passing \U0001f389, see [here]({run_url}) for details {run_tag}"
134 # Add thank-you when transitioning from failures to passing
135 if prev_count is not None and prev_count > 0:
136 author = _extract_pr_author(existing_body)
137 if author:
138 line += (
139 f"\n\nThank you @{author} for fixing those issues! \U0001f607\n"
140 f"This PR is now ready for human review, looping in @Lissy93 \U0001fae1"
141 )
142 return line
143
144 verb = "check is" if findings_count == 1 else "checks are"
145 edit_label = f"**Edit {next_edit}:**"
146 return (
147 f"{edit_label} - {resolved_prefix}{findings_count} {verb} still failing, "
148 f"see [here]({run_url}) for details {run_tag}"
149 )
150
151
152def write_output(action, body=""):
153 """Write action.txt and (optionally) final-comment.md."""
154 os.makedirs(WORK_DIR, exist_ok=True)
155 with open(os.path.join(WORK_DIR, "action.txt"), "w") as f:
156 f.write(action)
157 if body:
158 with open(os.path.join(WORK_DIR, "final-comment.md"), "w") as f:
159 f.write(body)
160
161
162def main():
163 check_run_id = os.environ.get("CHECK_RUN_ID", "")
164 repo = os.environ.get("GITHUB_REPOSITORY", "")
165
166 new_body = read_file(os.path.join(WORK_DIR, "comment.md"))
167 if not new_body:
168 write_output("skip")
169 return
170
171 existing_body = read_file(os.path.join(WORK_DIR, "existing-comment.md"))
172
173 # No existing comment — create a new one
174 if not existing_body:
175 write_output("create", new_body)
176 return
177
178 # Existing comment — build an edit line to append
179 if not check_run_id:
180 write_output("skip")
181 return
182
183 findings_count = read_findings_count(new_body)
184 edit_line = build_edit_line(existing_body, findings_count, check_run_id, repo)
185
186 # Refresh the Submission Info block even if findings haven't changed
187 refreshed_body = _refresh_submission_info(existing_body, new_body)
188 info_changed = refreshed_body != existing_body
189
190 if not edit_line and not info_changed:
191 write_output("skip")
192 return
193
194 updated = refreshed_body
195 if edit_line:
196 if "### Updates" in updated:
197 updated = updated.rstrip() + "\n" + edit_line
198 else:
199 updated = updated.rstrip() + "\n\n---\n\n### Updates\n\n" + edit_line
200 write_output("update", updated)
201
202
203if __name__ == "__main__":
204 main()