Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions WORKFLOW.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ conflicting issue fails that job, adds `claim-conflict`, and posts one comment.
Correct the body or issue state and synchronize/reopen the PR to recheck; a
successful recheck clears the label. Documentation-only and CI/test-only path
changes are exempt. `Refs` does not promise closure and is not checked.
GitHub links issues only from closing keywords in the PR body, never the
title. When the title has `Fixes #N` and the body names neither `Fixes #N`
nor `Refs #N`, the bot posts one comment (and a check warning) asking for
the body line, removes it once the body is fixed, and checks the claim on
#N as if the body closed it (#38).
The coordinator also rechecks live issue state before recommending enqueue,
so a closure or reassignment after the PR event cannot silently pass.
Callers must subscribe to the PR events above; a caller that only subscribes
Expand Down
121 changes: 118 additions & 3 deletions tests/test_pr_claims.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,27 @@
import unittest
from unittest.mock import Mock, patch

from workflow import claim_bot, coordinator
from workflow import claim_bot, coordinator, pr_claims
from workflow.sim import World

R = "obs-studio"


class PullRequestClaims(unittest.TestCase):
class PrEvents:
"""A simulated world and the PR events the claim bot gets."""

def setUp(self):
self.w = World()
self.addCleanup(self.w.shutdown)
self.w.gh.pr_files = Mock(return_value=["rust/obs-util/src/lib.rs"])

def event(self, body, author="alice", action="opened", labels=()):
def event(self, body, author="alice", action="opened", labels=(), title="A change"):
pr = self.w.open_pr(R, author)
return {
"action": action,
"pull_request": {
"number": pr,
"title": title,
"body": body,
"user": {"login": author},
"labels": [{"name": label} for label in labels],
Expand All @@ -31,6 +34,8 @@ def event(self, body, author="alice", action="opened", labels=()):
def check(self, event):
return claim_bot.on_pull_request(self.w.gh, R, event, self.w.now)


class PullRequestClaims(PrEvents, unittest.TestCase):
def test_closed_duplicate_is_flagged_even_with_same_account_assignment(self):
issue = self.w.open_issue(R, labels={"ready"})
self.w.comment(R, issue, "alice", "Claiming: original")
Expand Down Expand Up @@ -151,6 +156,106 @@ def test_rejected_comment_does_not_become_accepted_on_later_assignment(self):
self.assertFalse(self.check(self.event(f"Fixes #{issue}")))


class TitleOnlyClosingKeyword(PrEvents, unittest.TestCase):
"""obs-rust/.github#38: GitHub links issues only from closing keywords in
the PR body. obs-rust/obs-studio#5982, #5969 and #5987 named their issue
only in the title, and the issues stayed open after the merge."""

def claimed(self, user="alice"):
issue = self.w.open_issue(R, labels={"ready"})
self.w.comment(R, issue, user, "Claiming: fix")
return issue

def title_notes(self, pr):
return [b for b in self.w.bot_comments(R, pr) if b.startswith(pr_claims.TITLE_MARKER)]

def test_a_title_only_keyword_gets_one_comment(self):
issue = self.claimed()
event = self.event("Summary of the change", title=f"win-capture: a fix (Fixes #{issue})")
self.assertTrue(self.check(event))
event["action"] = "synchronize"
self.assertTrue(self.check(event))
pr = event["pull_request"]["number"]
notes = self.title_notes(pr)
self.assertEqual(len(notes), 1)
self.assertIn(f"`Fixes #{issue}`", notes[0])
self.assertIn("body", notes[0])
self.assertNotIn("claim-conflict", self.w.labels(R, pr))

def test_a_body_with_fixes_or_refs_gets_no_comment(self):
for body in ("Fixes #{n}", "Refs #{n}", "Refs: #{n}"):
with self.subTest(body=body):
issue = self.claimed()
event = self.event(body.format(n=issue), title=f"A fix (Fixes #{issue})")
self.check(event)
self.assertEqual(self.title_notes(event["pull_request"]["number"]), [])

def test_a_bare_reference_in_the_body_still_gets_a_comment(self):
# obs-rust/obs-studio#5969: "(#4455)" in the body links nothing.
issue = self.claimed()
event = self.event(f"Follow-up (#{issue})", title=f"A fix (Fixes #{issue})")
self.check(event)
self.assertEqual(len(self.title_notes(event["pull_request"]["number"])), 1)

def test_a_fixed_body_removes_the_comment(self):
issue = self.claimed()
event = self.event("", title=f"A fix (Fixes #{issue})")
self.check(event)
pr = event["pull_request"]["number"]
self.assertEqual(len(self.title_notes(pr)), 1)
event["action"] = "edited"
event["pull_request"]["body"] = f"Fixes #{issue}"
self.check(event)
self.assertEqual(self.title_notes(pr), [])

def test_a_keyword_in_backticks_in_the_title_is_ignored(self):
issue = self.claimed()
event = self.event("", title=f"docs: explain `Fixes #{issue}`")
self.check(event)
self.assertEqual(self.title_notes(event["pull_request"]["number"]), [])

def test_a_title_only_reference_gets_the_claim_check(self):
issue = self.claimed(user="bob")
event = self.event("", title=f"A fix (Fixes #{issue})")
self.assertFalse(self.check(event))
pr = event["pull_request"]["number"]
self.assertIn("claim-conflict", self.w.labels(R, pr))
self.assertTrue(any("bob" in b for b in self.w.bot_comments(R, pr)))

def test_a_revert_of_a_fixes_title_gets_no_note_and_no_conflict(self):
# The issue the reverted PR fixed is closed; a revert must still land.
issue = self.claimed()
self.w.close(R, issue)
event = self.event(
"Reverts obs-rust/obs-studio#1234", title=f'Revert "A fix (Fixes #{issue})"'
)
self.assertTrue(self.check(event))
pr = event["pull_request"]["number"]
self.assertEqual(self.w.bot_comments(R, pr), [])
self.assertNotIn("claim-conflict", self.w.labels(R, pr))

def test_an_exempt_docs_pr_still_gets_the_note(self):
self.w.gh.pr_files.return_value = ["docs/guide.md"]
issue = self.w.open_issue(R)
event = self.event("", title=f"docs: a guide (Fixes #{issue})")
self.assertTrue(self.check(event))
pr = event["pull_request"]["number"]
self.assertEqual(len(self.title_notes(pr)), 1)
self.assertNotIn("claim-conflict", self.w.labels(R, pr))

def test_a_changed_title_replaces_the_note(self):
first, second = self.claimed(), self.claimed()
event = self.event("", title=f"A fix (Fixes #{first})")
self.check(event)
event["action"] = "edited"
event["pull_request"]["title"] = f"A fix (Fixes #{second})"
self.check(event)
notes = self.title_notes(event["pull_request"]["number"])
self.assertEqual(len(notes), 1)
self.assertIn(f"#{second}", notes[0])
self.assertNotIn(f"`Fixes #{first}`", notes[0])


class RestClaimActions(unittest.TestCase):
def test_pr_label_add_uses_the_issues_rest_permission(self):
from workflow.gh import GhBackend
Expand Down Expand Up @@ -188,6 +293,16 @@ def test_pr_comment_uses_the_issues_rest_permission(self):
],
)

def test_delete_comment_uses_the_issues_rest_permission(self):
from workflow.gh import GhBackend

with patch("workflow.gh.run", return_value="") as run:
GhBackend().apply_issue("obs-rust/obs-studio", 3519, ("delete_comment", 42))
self.assertEqual(
run.call_args.args[0],
["gh", "api", "-X", "DELETE", "repos/obs-rust/obs-studio/issues/comments/42"],
)

def test_label_remove_encodes_its_path_component(self):
from workflow.gh import GhBackend

Expand Down
22 changes: 21 additions & 1 deletion workflow/claim_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,18 +95,38 @@ def on_pull_request(gh, repo: str, event: dict, now: datetime, dry_run: bool = F
)
elif pr_claims.LABEL in current.labels:
actions.append(("label_remove", pr_claims.LABEL))
actions += title_note_actions(repo, pr, current)
for action in actions:
try:
apply(gh, repo, pr["number"], [action], dry_run)
except GhError as error:
if action[0] not in {"label_add", "label_remove", "comment", "react"}:
if action[0] not in {"label_add", "label_remove", "comment", "react", "delete_comment"}:
raise
log(f"::warning::{repo}#{pr['number']}: {action[0]} failed: {error}")
if reasons:
report(reasons)
return not reasons


def title_note_actions(repo: str, pr: dict, current) -> list[tuple]:
"""Keep one comment while a closing keyword is only in the title (#38).

A note, not a conflict: it never fails the check. A fork PR's token
cannot comment, so the note also goes to the check as a warning.
"""
refs = pr_claims.title_only(repo, pr)
notes = [c for c in current.comments if c.body.startswith(pr_claims.TITLE_MARKER)]
note = pr_claims.title_note(repo, refs) if refs else None
if note:
data = note.removeprefix(pr_claims.TITLE_MARKER).strip()
print(f"::warning title=Closing keyword in the title::{data}", flush=True)
# The same note stays; a stale one (other issues, or none) goes.
actions = [("delete_comment", c.id) for c in notes if c.body != note]
if note and not any(c.body == note for c in notes):
actions.append(("comment", note))
return actions


HOW_TO_FIX = (
"Comment `Claiming: <plan>` on the issue (it must be Ready), ask a maintainer "
"for `/reassign`, or change the closing reference to `Refs #N`. Then push or "
Expand Down
3 changes: 2 additions & 1 deletion workflow/gh.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,13 +266,14 @@ def apply_issue(self, repo: str, number: int, action: tuple) -> None:
"-f",
f"body={arg}",
],
"delete_comment": ["gh", "api", "-X", "DELETE", f"repos/{repo}/issues/comments/{arg}"],
}[kind]
try:
run(cmd)
except GhError as error:
# The label or assignee is already gone: the issue is in the state
# the bot wants, and the actions after this one must still run.
if kind in {"label_remove", "unassign"} and error.status == 404:
if kind in {"label_remove", "unassign", "delete_comment"} and error.status == 404:
print(f"{repo}#{number}: {kind} {arg!r} already done (HTTP 404)")
return
raise
Expand Down
59 changes: 51 additions & 8 deletions workflow/pr_claims.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,66 @@

LABEL = "claim-conflict"
MARKER = "<!-- obs-rust:pr-claim-check -->"
CLOSING = re.compile(
r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*:?\s+"
TITLE_MARKER = "<!-- obs-rust:pr-title-keyword -->"
TARGET = (
r"(?:(?P<repo>[\w.-]+/[\w.-]+)?#(?P<number>\d+)"
r"|https://github\.com/(?P<urlrepo>[\w.-]+/[\w.-]+)/issues/(?P<urlnumber>\d+))",
re.IGNORECASE,
r"|https://github\.com/(?P<urlrepo>[\w.-]+/[\w.-]+)/issues/(?P<urlnumber>\d+))"
)
CLOSING = re.compile(r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*:?\s+" + TARGET, re.IGNORECASE)
# `Refs #N` is the documented way to name an issue a PR does not complete.
REFS = re.compile(r"\brefs?\s*:?\s+" + TARGET, re.IGNORECASE)


def references(repo, body):
def _matches(pattern, repo, text):
# Examples in fenced code or inline code do not close GitHub issues.
body = re.sub(r"```.*?```|`[^`\n]*`|<!--.*?-->", "", body or "", flags=re.S)
text = re.sub(r"```.*?```|`[^`\n]*`|<!--.*?-->", "", text or "", flags=re.S)
return sorted(
{
(m["repo"] or m["urlrepo"] or repo, int(m["number"] or m["urlnumber"]))
for m in CLOSING.finditer(body)
for m in pattern.finditer(text)
}
)


def references(repo, body):
return _matches(CLOSING, repo, body)


def title_only(repo, pr):
"""Closing references in the PR title that the body does not name.

GitHub links issues only from the body, so the merge does not close
these (#38). A body that names the issue with `Refs` chose not to close
it, which is fine; a bare `(#N)` in the body links nothing.
"""
title = pr.get("title") or ""
# GitHub titles a revert `Revert "<original title>"`: the original's
# keyword names an issue the revert does not close (it is often closed).
if title.startswith('Revert "'):
return []
body = pr.get("body")
named = set(references(repo, body)) | set(_matches(REFS, repo, body))
return [ref for ref in references(repo, title) if ref not in named]


def title_note(repo, refs):
names = [_name(repo, r) for r in refs]
fixes = ", ".join(f"`Fixes {n}`" for n in names)
return (
TITLE_MARKER
+ f"\nThe title has a closing keyword for {', '.join(names)}, but GitHub links "
+ "issues only from closing keywords in the PR body, so the merge will not close "
+ ("it" if len(refs) == 1 else "them")
+ f". Add {fixes} to the body, or `Refs` if this PR does not complete the issue. "
+ "This comment goes away when the body is fixed."
)


def _name(repo, ref):
target, number = ref
return f"#{number}" if target == repo else f"{target}#{number}"


def exempt(files):
return bool(files) and all(
p.endswith(".md")
Expand All @@ -35,7 +76,9 @@ def exempt(files):


def conflicts(gh, repo, pr):
refs = references(repo, pr.get("body"))
# A title-only keyword does not close the issue, but it says the author
# means to: check its claim too, so the title cannot skip this check.
refs = sorted(set(references(repo, pr.get("body"))) | set(title_only(repo, pr)))
if not refs or exempt(gh.pr_files(repo, pr["number"])):
return []
reasons = []
Expand Down
2 changes: 2 additions & 0 deletions workflow/sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,8 @@ def apply_issue(self, repo: str, number: int, action: tuple) -> None:
self.x("DELETE FROM assignees WHERE item=? AND login=?", item, arg)
elif kind == "react":
self.x("INSERT INTO reactions VALUES (?,?,?)", arg, BOT, REACTION)
elif kind == "delete_comment":
self.x("DELETE FROM comments WHERE id=?", arg)
elif kind == "comment":
self.x(
"INSERT INTO comments (item, author, assoc, body, created) VALUES (?,?,?,?,?)",
Expand Down
Loading