lib/checks/prepare-comment.py

220 lines · 8411 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 logging
 14import os
 15import re
 16import sys
 17
 18sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
 19import utils
 20
 21utils.setup_logging()
 22logger = logging.getLogger(__name__)
 23
 24WORK_DIR = "pr-meta"
 25
 26
 27def read_file(path):
 28    """Read a file and return its stripped content, or None if missing/empty."""
 29    try:
 30        with open(path) as f:
 31            content = f.read().strip()
 32            return content if content else None
 33    except Exception:
 34        return None
 35
 36
 37def read_findings_count(new_body):
 38    """Return the findings count from findings-count.txt, or by counting bullets."""
 39    raw = read_file(os.path.join(WORK_DIR, "findings-count.txt"))
 40    if raw is not None:
 41        try:
 42            return int(raw)
 43        except ValueError:
 44            pass
 45    # Fallback: count bullet lines before <details> (diff summary has its own bullets)
 46    body_before_details = new_body.split("<details>")[0]
 47    return len(re.findall(r"^- .+$", body_before_details, re.MULTILINE))
 48
 49
 50def _was_already_passing(existing_body):
 51    """Check if the most recent state in the comment is already all-clear."""
 52    # If there's a previous "all passing" edit, the last state was passing
 53    if re.search(r"^(?:\*\*)?Edit(?: \d+)?(?:\*\*)?: (?:- )?All checks are (now passing|passing now)", existing_body, re.MULTILINE):
 54        return True
 55    # If there are no edits at all, check the original comment body
 56    if not re.search(r"^(?:\*\*)?Edit(?: \d+)?(?:\*\*)?:", existing_body, re.MULTILINE):
 57        return "All our automated checks have passed" in existing_body
 58    return False
 59
 60
 61def _previous_failing_count(existing_body):
 62    """Extract the findings count from the most recent state in the comment."""
 63    # Check edit lines first (most recent state)
 64    matches = re.findall(r"^(?:\*\*)?Edit(?: \d+)?(?:\*\*)?: (?:- )?(\d+) checks? (?:is|are) still failing", existing_body, re.MULTILINE)
 65    if matches:
 66        return int(matches[-1])
 67    # No edits — count bullets in the original comment (before <details>)
 68    if not re.search(r"^(?:\*\*)?Edit(?: \d+)?(?:\*\*)?:", existing_body, re.MULTILINE):
 69        body_before_details = existing_body.split("<details>")[0]
 70        bullets = re.findall(r"^- .+$", body_before_details, re.MULTILINE)
 71        return len(bullets) if bullets else None
 72    return None
 73
 74
 75def _extract_pr_author(existing_body):
 76    """Extract the PR author username from the 'Hello @user' greeting."""
 77    match = re.search(r"Hello @([\w-]+)", existing_body)
 78    return match.group(1) if match else None
 79
 80
 81_SUBMISSION_INFO_RE = re.compile(
 82    r"<details><summary>Submission Info</summary>\s*\n.*?</details>",
 83    re.DOTALL,
 84)
 85
 86
 87def _extract_submission_info(body):
 88    """Extract the Submission Info <details> block, or None if absent."""
 89    match = _SUBMISSION_INFO_RE.search(body)
 90    return match.group(0) if match else None
 91
 92
 93def _refresh_submission_info(existing_body, new_body):
 94    """Replace or insert the Submission Info block from new_body into existing_body."""
 95    new_block = _extract_submission_info(new_body)
 96    if not new_block:
 97        return existing_body
 98    old_block = _extract_submission_info(existing_body)
 99    if old_block:
100        if old_block == new_block:
101            return existing_body
102        return existing_body.replace(old_block, new_block)
103    # No existing block — insert before Updates section or workflow run link
104    for anchor in ("---\n\n### Updates", "<sup>For full details"):
105        if anchor in existing_body:
106            return existing_body.replace(anchor, new_block + "\n\n" + anchor, 1)
107    return existing_body.rstrip() + "\n\n" + new_block
108
109
110def build_edit_line(existing_body, findings_count, check_run_id, repo):
111    """Build the edit line to append, or None if nothing to do."""
112    run_tag = f"<!-- run:{check_run_id} -->"
113
114    # Idempotency: this run was already processed
115    if run_tag in existing_body:
116        return None
117
118    # Skip if the state hasn't changed
119    if findings_count == 0 and _was_already_passing(existing_body):
120        return None
121    if findings_count > 0 and _previous_failing_count(existing_body) == findings_count:
122        return None
123
124    # Count previous edits to determine the next number
125    edits = re.findall(r"^(?:\*\*)?Edit(?: \d+)?(?:\*\*)?:", existing_body, re.MULTILINE)
126    edit_count = len(edits)
127    next_edit = edit_count + 1
128
129    run_url = f"https://github.com/{repo}/actions/runs/{check_run_id}"
130
131    # Build resolved-issue prefix
132    prev_count = _previous_failing_count(existing_body)
133    resolved_prefix = ""
134    if prev_count is not None and prev_count > findings_count:
135        resolved = prev_count - findings_count
136        noun = "issue was" if resolved == 1 else "issues were"
137        resolved_prefix = f"{resolved} {noun} resolved, but "
138
139    if findings_count == 0:
140        edit_label = "**Edit:**" if edit_count == 0 else f"**Edit {next_edit}:**"
141        line = f"{edit_label} - All checks are now passing \U0001f389, see [here]({run_url}) for details {run_tag}"
142        # Add thank-you when transitioning from failures to passing
143        if prev_count is not None and prev_count > 0:
144            author = _extract_pr_author(existing_body)
145            if author:
146                line += (
147                    f"\n\nThank you @{author} for fixing those issues! \U0001f607\n"
148                    f"This PR is now ready for human review, looping in @Lissy93 \U0001fae1"
149                )
150        return line
151
152    verb = "check is" if findings_count == 1 else "checks are"
153    edit_label = f"**Edit {next_edit}:**"
154    return (
155        f"{edit_label} - {resolved_prefix}{findings_count} {verb} still failing, "
156        f"see [here]({run_url}) for details {run_tag}"
157    )
158
159
160def write_output(action, body=""):
161    """Write action.txt and (optionally) final-comment.md."""
162    os.makedirs(WORK_DIR, exist_ok=True)
163    with open(os.path.join(WORK_DIR, "action.txt"), "w") as f:
164        f.write(action)
165    if body:
166        with open(os.path.join(WORK_DIR, "final-comment.md"), "w") as f:
167            f.write(body)
168
169
170def main():
171    logger.info("Preparing PR bot comment (deciding create/update/skip)")
172    check_run_id = os.environ.get("CHECK_RUN_ID", "")
173    repo = os.environ.get("GITHUB_REPOSITORY", "")
174
175    new_body = read_file(os.path.join(WORK_DIR, "comment.md"))
176    if not new_body:
177        logger.info("No new comment.md to post, action=skip")
178        write_output("skip")
179        return
180
181    existing_body = read_file(os.path.join(WORK_DIR, "existing-comment.md"))
182
183    # No existing comment — create a new one
184    if not existing_body:
185        logger.info("No existing bot comment, action=create")
186        write_output("create", new_body)
187        return
188
189    # Existing comment — build an edit line to append
190    if not check_run_id:
191        logger.info("Existing comment but no CHECK_RUN_ID, action=skip")
192        write_output("skip")
193        return
194
195    findings_count = read_findings_count(new_body)
196    logger.info("Existing comment found, new run reports %d finding(s)", findings_count)
197    edit_line = build_edit_line(existing_body, findings_count, check_run_id, repo)
198
199    # Refresh the Submission Info block even if findings haven't changed
200    refreshed_body = _refresh_submission_info(existing_body, new_body)
201    info_changed = refreshed_body != existing_body
202
203    if not edit_line and not info_changed:
204        logger.info("State unchanged and submission info unchanged, action=skip")
205        write_output("skip")
206        return
207
208    updated = refreshed_body
209    if edit_line:
210        if "### Updates" in updated:
211            updated = updated.rstrip() + "\n" + edit_line
212        else:
213            updated = updated.rstrip() + "\n\n---\n\n### Updates\n\n" + edit_line
214    logger.info("Updating comment (new edit=%s, submission info changed=%s), action=update",
215                bool(edit_line), info_changed)
216    write_output("update", updated)
217
218
219if __name__ == "__main__":
220    main()