Skip to content

Commit

Permalink
Add reminder comment
Browse files Browse the repository at this point in the history
  • Loading branch information
JordonPhillips committed Nov 19, 2024
1 parent f6797be commit c007616
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 19 deletions.
34 changes: 26 additions & 8 deletions .changes/tool/amend.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
from pathlib import Path

from . import REPO_ROOT, Change
from .github import post_review_comment
from .github import post_comment, post_review_comment

DEFAULT_REPO = "smithy-lang/smithy"
GITHUB_URL = os.environ.get("GITHUB_SERVER_URL", "https://github.com")


def amend(
Expand All @@ -32,9 +33,31 @@ def amend(
pr_number = pr_number.split("/")[0]

repository = repository or os.environ.get("GITHUB_REPOSITORY", DEFAULT_REPO)
pr_ref = get_pr_ref(pr_number=pr_number, repository=repository)
pr_ref = f"[#{pr_number}]({GITHUB_URL}/{repository}/pull/{pr_number})"

for change_file, change in get_new_changes(base).items():
changes = get_new_changes(base)
if review_comment:
print("No changelog found, adding reminder comment.")
description = os.environ.get("PR_TITLE", "Example description").replace(
'"', '\\"'
)
comment = (
"This pull request does not contain a staged changelog entry. To create "
"one, use the `./.changes/new-change` command. For example:\n\n"
f"```\n./.changes/new-change --pull-requests #{pr_number} --type feature "
f'--description "{description}"\n```\n\n'
"Make sure that the description is appropriate for a changelog entry and "
"that the proper feature type is used. See [`./.changes/README`]("
f"{GITHUB_URL}/{repository}/tree/main/.changes/README) or run "
"`./.changes/new-change -h` for more information."
)
post_comment(
repository=repository,
pr_number=pr_number,
comment=comment,
)

for change_file, change in changes.items():
if not change.pull_requests:
print(f"Amending changelog entry without associated prs: {change_file}")
change.pull_requests = [pr_ref]
Expand All @@ -60,11 +83,6 @@ def amend(
change.write(change_file)


def get_pr_ref(pr_number: str | None, repository: str):
base_url = os.environ.get("GITHUB_SERVER_URL", "https://github.com")
return f"[#{pr_number}]({base_url}/{repository}/pull/{pr_number})"


def get_new_changes(base: str | None) -> dict[Path, Change]:
base = base or os.environ.get("GITHUB_BASE_REF", "main")
print(f"Running a diff against base branch: {base}")
Expand Down
57 changes: 46 additions & 11 deletions .changes/tool/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,20 @@ class User(TypedDict):
login: Required[str]


class ReviewComment(TypedDict):
class Comment(TypedDict):
user: Required[User]
path: Required[str]
body: str


class ReviewComment(Comment):
path: Required[str]


# https://docs.github.com/en/rest/pulls/comments?apiVersion=2022-11-28#list-review-comments-on-a-pull-request
def get_review_comments(
repository: str,
pr_number: str,
) -> Generator[ReviewComment]:
_assert_token()
url = f"{GITHUB_API_URL}/repos/{repository}/pulls/{pr_number}/comments?per_page=100"
for response in _paginate(url):
if not isinstance(response.body, list):
Expand All @@ -109,6 +111,42 @@ def get_review_comments(
yield comment # type: ignore


# https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28#create-an-issue-comment
def post_comment(
repository: str,
pr_number: str,
comment: str,
allow_duplicate: bool = False,
) -> None:
if not allow_duplicate:
for existing_comment in get_review_comments(repository, pr_number):
if existing_comment["body"] == comment:
print("Review comment already posted, skipping duplicate.")
return

_request(
url=f"{GITHUB_API_URL}/repos/{repository}/issues/{pr_number}/comments",
body={"body": comment},
)


# https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28#list-issue-comments
def get_comments(
repository: str,
pr_number: str,
) -> Generator[Comment]:
url = (
f"{GITHUB_API_URL}/repos/{repository}/issues/{pr_number}/comments?per_page=100"
)
for response in _paginate(url):
if not isinstance(response.body, list):
raise ValueError(
f"Expected list body, but found {type(response.body)}: {response.body}"
)
for comment in response.body:
yield comment # type: ignore


@dataclass
class JSONResponse:
headers: dict[str, str]
Expand All @@ -125,7 +163,11 @@ def from_http_response(cls, http_response: HTTPResponse) -> Self:


def _request(url: str, body: JSON = None) -> JSONResponse:
_assert_token()
if not GITHUB_TOKEN:
raise ValueError(
"The GITHUB_TOKEN environment variable must be set to post review comments."
)

headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {GITHUB_TOKEN}",
Expand Down Expand Up @@ -173,10 +215,3 @@ def __init__(self, response: HTTPError) -> None:
json.loads(response.read().decode("utf-8")), indent=2
)
super().__init__(f"GitHub API request failed:\n\n{formatted_body}")


def _assert_token():
if not GITHUB_TOKEN:
raise ValueError(
"The GITHUB_TOKEN environment variable must be set to post review comments."
)
1 change: 1 addition & 0 deletions .github/workflows/amend-new-changelogs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ jobs:
env:
GITHUB_TOKEN: ${{ github.token }}
TARGET_SHA: ${{ github.event.pull_request.head.sha }}
PR_TITLE: ${{ github.event.pull_request.title }}
run: |
git fetch origin ${{ github.base_ref }}
./.changes/amend --review-comment

0 comments on commit c007616

Please sign in to comment.