Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor update_comment() #354

Merged
merged 1 commit into from
Oct 27, 2024
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
4 changes: 2 additions & 2 deletions services/check_run_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def handle_check_run(payload: CheckRunCompletedPayload) -> None:

# Plan how to fix the error
comment_body = create_progress_bar(p=30, msg="Planning how to fix the error...")
update_comment(comment_url=comment_url, token=token, body=comment_body)
update_comment(body=comment_body, base_args=base_args)
input_message: dict[str, str] = {
"pull_request_title": pull_title,
"pull_request_body": pull_body,
Expand Down Expand Up @@ -215,5 +215,5 @@ def handle_check_run(payload: CheckRunCompletedPayload) -> None:

# Create a pull request to the base branch
msg = f"Committed the Check Run `{check_run_name}` error fix! Running it again..."
update_comment(comment_url=comment_url, token=token, body=msg)
update_comment(body=msg, base_args=base_args)
return
16 changes: 6 additions & 10 deletions services/gitauto_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ async def handle_gitauto(payload: GitHubLabeledPayload, trigger_type: str) -> No

# Prepare PR body
comment_body = create_progress_bar(p=10, msg="Writing a pull request body...")
update_comment(comment_url=comment_url, token=token, body=comment_body)
update_comment(body=comment_body, base_args=base_args)
pr_body: str = chat_with_ai(
system_input=WRITE_PR_BODY,
user_input=json.dumps(
Expand All @@ -172,22 +172,18 @@ async def handle_gitauto(payload: GitHubLabeledPayload, trigger_type: str) -> No
)
base_args["pr_body"] = pr_body

messages = [{"role": "user", "content": pr_body}]
hiroshinishio marked this conversation as resolved.
Show resolved Hide resolved
# Create a remote branch
comment_body = create_progress_bar(p=20, msg="Creating a remote branch...")
update_comment(comment_url=comment_url, token=token, body=comment_body)
update_comment(body=comment_body, base_args=base_args)
latest_commit_sha: str = get_latest_remote_commit_sha(
unique_issue_id=unique_issue_id,
clone_url=repo["clone_url"],
base_args=base_args,
)
create_remote_branch(sha=latest_commit_sha, base_args=base_args)
comment_body = create_progress_bar(p=30, msg="Thinking about how to code...")
update_comment(comment_url=comment_url, token=token, body=comment_body)

truncated_msg: str = truncate_message(input_message=pr_body)
messages = [
{"role": "user", "content": truncated_msg if truncated_msg else pr_body},
]
update_comment(body=comment_body, base_args=base_args)

# Loop a process explore repo and commit changes until the ticket is resolved
previous_calls = []
Expand Down Expand Up @@ -234,7 +230,7 @@ async def handle_gitauto(payload: GitHubLabeledPayload, trigger_type: str) -> No

# Create a pull request to the base branch
comment_body = create_progress_bar(p=90, msg="Creating a pull request...")
update_comment(comment_url=comment_url, token=token, body=comment_body)
update_comment(body=comment_body, base_args=base_args)
title = f"{PRODUCT_NAME}: {issue_title}"
issue_link: str = f"{PR_BODY_STARTS_WITH}{issue_number}\n\n"
pr_body = issue_link + pr_body + git_command(new_branch_name=new_branch_name)
Expand All @@ -252,7 +248,7 @@ async def handle_gitauto(payload: GitHubLabeledPayload, trigger_type: str) -> No
else:
is_completed = False
body_after_pr = UPDATE_COMMENT_FOR_422
update_comment(comment_url=comment_url, token=token, body=body_after_pr)
update_comment(body=body_after_pr, base_args=base_args)

end_time = time.time()
supabase_manager.complete_and_update_usage_record(
Expand Down
73 changes: 7 additions & 66 deletions services/github/github_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,7 @@
from utils.file_manager import apply_patch, get_file_content, run_command
from utils.handle_exceptions import handle_exceptions
from utils.parse_urls import parse_github_url
from utils.text_copy import (
UPDATE_COMMENT_FOR_422,
UPDATE_COMMENT_FOR_RAISED_ERRORS_NO_CHANGES_MADE,
request_issue_comment,
request_limit_reached,
)
from utils.text_copy import request_issue_comment, request_limit_reached


@handle_exceptions(default_return_value=None, raise_on_error=False)
Expand Down Expand Up @@ -465,16 +460,16 @@ def get_issue_comments(
return comment_texts


@handle_exceptions(raise_on_error=True)
def get_latest_remote_commit_sha(
unique_issue_id: str, clone_url: str, base_args: BaseArgs
) -> str:
"""SHA stands for Secure Hash Algorithm. It's a unique identifier for a commit.
https://docs.github.com/en/rest/git/refs?apiVersion=2022-11-28#get-a-reference"""
owner, repo, branch, comment_url = (
owner, repo, branch = (
base_args["owner"],
base_args["repo"],
base_args["base_branch"],
base_args["comment_url"],
)
token = base_args["token"]
try:
Expand All @@ -501,12 +496,8 @@ def get_latest_remote_commit_sha(
)
raise
except Exception as e:
hiroshinishio marked this conversation as resolved.
Show resolved Hide resolved
update_comment_for_raised_errors(
error=e,
comment_url=comment_url,
token=token,
which_function=get_latest_remote_commit_sha.__name__,
)
msg = f"{get_latest_remote_commit_sha.__name__} encountered an error: {e}"
update_comment(body=msg, base_args=base_args)
# Raise an error because we can't continue without the latest commit SHA
raise RuntimeError(
f"Error: Could not get the latest commit SHA in {get_latest_remote_commit_sha.__name__}"
Expand Down Expand Up @@ -773,8 +764,9 @@ async def verify_webhook_signature(request: Request, secret: str) -> None:


@handle_exceptions(default_return_value=None, raise_on_error=False)
def update_comment(comment_url: str, body: str, token: str) -> dict[str, Any]:
def update_comment(body: str, base_args: BaseArgs) -> dict[str, Any]:
"""https://docs.github.com/en/rest/issues/comments#update-an-issue-comment"""
comment_url, token = base_args["comment_url"], base_args["token"]
print(body + "\n")
response: requests.Response = requests.patch(
url=comment_url,
Expand All @@ -784,54 +776,3 @@ def update_comment(comment_url: str, body: str, token: str) -> dict[str, Any]:
)
response.raise_for_status()
return response.json()


def update_comment_for_raised_errors(
error: Any, comment_url: str, token: str, which_function: str
) -> dict[str, Any]:
"""Update the comment on issue with an error message and raise the error."""
body = UPDATE_COMMENT_FOR_422
try:
if isinstance(error, requests.exceptions.HTTPError):
logging.error(
"%s HTTP Error: %s - %s",
which_function,
error.response.status_code,
error.response.text,
)
if (
error.response.status_code == 422
and error["message"]
and error.message == "Validation Failed"
and (
(
isinstance(error.errors[0], list)
and hasattr(error.errors[0][0], "message")
and error.errors[0][0].message.find(
"No commits between main and"
)
!= -1
)
or (
not isinstance(error.errors[0], list)
and hasattr(error.errors[0], "message")
and error.errors[0].message.find("No commits between main and")
!= -1
)
)
):
body = UPDATE_COMMENT_FOR_RAISED_ERRORS_NO_CHANGES_MADE
else:
logging.error(
"%s HTTP Error: %s - %s",
which_function,
error.response.status_code,
error.response.text,
)
else:
logging.error("%s Error: %s", which_function, error)
except Exception as e: # pylint: disable=broad-except
logging.error("%s Error: %s", which_function, e)
update_comment(comment_url=comment_url, token=token, body=body)

raise RuntimeError("Error occurred")