Skip to content

Commit da2efa9

Browse files
feat: Add script to fetch PR review comments
This commit introduces a new script `scripts/gha/get_pr_review_comments.py` that allows you to fetch review comments from a specified GitHub Pull Request. The comments are formatted to include the commenter, file path, line number, diff hunk, and the comment body, making it easy to paste into me for review. The script utilizes a new function `get_pull_request_review_comments` added to the existing `scripts/gha/firebase_github.py` library. This new function handles fetching line-specific comments from the GitHub API, including pagination. The script takes a PR number as a required argument and can optionally take repository owner, repository name, and GitHub token as arguments, with the token also being configurable via the GITHUB_TOKEN environment variable.
1 parent a06d206 commit da2efa9

File tree

2 files changed

+154
-0
lines changed

2 files changed

+154
-0
lines changed

scripts/gha/firebase_github.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,37 @@ def get_reviews(token, pull_number):
225225
return results
226226

227227

228+
def get_pull_request_review_comments(token, pull_number):
229+
"""https://docs.github.com/en/rest/pulls/comments#list-review-comments-on-a-pull-request"""
230+
url = f'{GITHUB_API_URL}/pulls/{pull_number}/comments'
231+
headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'}
232+
page = 1
233+
per_page = 100
234+
results = []
235+
keep_going = True
236+
while keep_going:
237+
params = {'per_page': per_page, 'page': page}
238+
page = page + 1
239+
keep_going = False
240+
# Use a try-except block to catch potential errors during the API request
241+
try:
242+
with requests_retry_session().get(url, headers=headers, params=params,
243+
stream=True, timeout=TIMEOUT) as response:
244+
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
245+
logging.info("get_pull_request_review_comments: %s page %s response: %s", url, params.get('page'), response)
246+
current_page_results = response.json()
247+
if not current_page_results: # No more results
248+
break
249+
results.extend(current_page_results)
250+
# If exactly per_page results were retrieved, there might be more.
251+
keep_going = (len(current_page_results) == per_page)
252+
except requests.exceptions.RequestException as e:
253+
logging.error(f"Error fetching review comments page {params.get('page')-1} for PR {pull_number}: {e}")
254+
# Optionally, re-raise the exception or handle it by returning partial results or an empty list
255+
break # Stop trying if there's an error
256+
return results
257+
258+
228259
def create_workflow_dispatch(token, workflow_id, ref, inputs):
229260
"""https://docs.github.com/en/rest/reference/actions#create-a-workflow-dispatch-event"""
230261
url = f'{GITHUB_API_URL}/actions/workflows/{workflow_id}/dispatches'

scripts/gha/get_pr_review_comments.py

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
#!/usr/bin/env python3
2+
# Copyright 2024 Google LLC
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
"""Fetches and formats review comments from a GitHub Pull Request."""
17+
18+
import argparse
19+
import os
20+
import sys
21+
import firebase_github # Assumes firebase_github.py is in the same directory or python path
22+
23+
# Attempt to configure logging for firebase_github if absl is available
24+
try:
25+
from absl import logging as absl_logging
26+
# Set verbosity for absl logging if you want to see logs from firebase_github
27+
# absl_logging.set_verbosity(absl_logging.INFO)
28+
except ImportError:
29+
# If absl is not used, standard logging can be configured if needed
30+
# import logging as std_logging
31+
# std_logging.basicConfig(level=std_logging.INFO)
32+
pass # firebase_github.py uses absl.logging.info, so this won't redirect.
33+
34+
35+
def main():
36+
# Default owner and repo from firebase_github, ensuring it's loaded.
37+
default_owner = firebase_github.OWNER
38+
default_repo = firebase_github.REPO
39+
40+
parser = argparse.ArgumentParser(
41+
description="Fetch review comments from a GitHub PR and format for use with Jules.",
42+
formatter_class=argparse.RawTextHelpFormatter # To preserve formatting in help text
43+
)
44+
parser.add_argument(
45+
"--pull_number",
46+
type=int,
47+
required=True,
48+
help="Pull request number."
49+
)
50+
parser.add_argument(
51+
"--owner",
52+
type=str,
53+
default=default_owner,
54+
help=f"Repository owner. Defaults to '{default_owner}' (from firebase_github.py)."
55+
)
56+
parser.add_argument(
57+
"--repo",
58+
type=str,
59+
default=default_repo,
60+
help=f"Repository name. Defaults to '{default_repo}' (from firebase_github.py)."
61+
)
62+
parser.add_argument(
63+
"--token",
64+
type=str,
65+
default=os.environ.get("GITHUB_TOKEN"),
66+
help="GitHub token. Can also be set via GITHUB_TOKEN environment variable."
67+
)
68+
69+
args = parser.parse_args()
70+
71+
if not args.token:
72+
sys.stderr.write("Error: GitHub token not provided. Set GITHUB_TOKEN environment variable or use --token argument.\n")
73+
sys.exit(1)
74+
75+
# Update the repository details in firebase_github module if different from default
76+
if args.owner != firebase_github.OWNER or args.repo != firebase_github.REPO:
77+
repo_url = f"https://github.com/{args.owner}/{args.repo}"
78+
if not firebase_github.set_repo_url(repo_url):
79+
sys.stderr.write(f"Error: Invalid repository URL format for {args.owner}/{args.repo}. Expected format: https://github.com/owner/repo\n")
80+
sys.exit(1)
81+
# Using print to stderr for info, as absl logging might not be configured here for this script's own messages.
82+
print(f"Targeting repository: {firebase_github.OWNER}/{firebase_github.REPO}", file=sys.stderr)
83+
84+
85+
print(f"Fetching review comments for PR #{args.pull_number} from {firebase_github.OWNER}/{firebase_github.REPO}...", file=sys.stderr)
86+
87+
comments = firebase_github.get_pull_request_review_comments(args.token, args.pull_number)
88+
89+
if not comments: # This will be true if list is empty (no comments or error in fetching first page)
90+
print(f"No review comments found for PR #{args.pull_number}, or an error occurred during fetching.", file=sys.stderr)
91+
# If firebase_github.py's get_pull_request_review_comments logs errors, those might provide more details.
92+
return # Exit gracefully if no comments
93+
94+
# Output actual data to stdout
95+
print("\n--- Review Comments ---")
96+
for comment in comments:
97+
user = comment.get("user", {}).get("login", "Unknown user")
98+
path = comment.get("path", "N/A")
99+
line = comment.get("line", "N/A")
100+
body = comment.get("body", "").strip() # Strip whitespace from comment body
101+
diff_hunk = comment.get("diff_hunk", "N/A")
102+
html_url = comment.get("html_url", "N/A")
103+
104+
# Only print comments that have a body
105+
if not body:
106+
continue
107+
108+
print(f"Comment by: {user}")
109+
print(f"File: {path}")
110+
# The 'line' field in GitHub's API for PR review comments refers to the line number in the diff.
111+
# 'original_line' refers to the line number in the file at the time the comment was made.
112+
# 'start_line' and 'original_start_line' for multi-line comments.
113+
# For simplicity, we use 'line'.
114+
print(f"Line in diff: {line}")
115+
print(f"URL: {html_url}")
116+
print("--- Diff Hunk ---")
117+
print(diff_hunk)
118+
print("--- Comment ---")
119+
print(body)
120+
print("----------------------------------------\n")
121+
122+
if __name__ == "__main__":
123+
main()

0 commit comments

Comments
 (0)