From c75be5fb57a2702159550bbea49222af7f6a3b83 Mon Sep 17 00:00:00 2001 From: Hiroshi Nishio Date: Sun, 27 Oct 2024 15:36:03 -0700 Subject: [PATCH] Refactor update_comment() --- services/check_run_handler.py | 4 +- services/gitauto_handler.py | 16 +++---- services/github/github_manager.py | 73 +++---------------------------- 3 files changed, 15 insertions(+), 78 deletions(-) diff --git a/services/check_run_handler.py b/services/check_run_handler.py index d1431812..1b20399b 100644 --- a/services/check_run_handler.py +++ b/services/check_run_handler.py @@ -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, @@ -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 diff --git a/services/gitauto_handler.py b/services/gitauto_handler.py index 40bbd14c..4a511229 100644 --- a/services/gitauto_handler.py +++ b/services/gitauto_handler.py @@ -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( @@ -172,9 +172,10 @@ async def handle_gitauto(payload: GitHubLabeledPayload, trigger_type: str) -> No ) base_args["pr_body"] = pr_body + messages = [{"role": "user", "content": pr_body}] # 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"], @@ -182,12 +183,7 @@ async def handle_gitauto(payload: GitHubLabeledPayload, trigger_type: str) -> No ) 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 = [] @@ -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) @@ -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( diff --git a/services/github/github_manager.py b/services/github/github_manager.py index 049349c6..a5c141da 100644 --- a/services/github/github_manager.py +++ b/services/github/github_manager.py @@ -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) @@ -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: @@ -501,12 +496,8 @@ def get_latest_remote_commit_sha( ) raise except Exception as e: - 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__}" @@ -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, @@ -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")