|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2025 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 |
| 22 | +import datetime |
| 23 | +from datetime import timezone, timedelta |
| 24 | + |
| 25 | + |
| 26 | +def main(): |
| 27 | + STATUS_IRRELEVANT = "[IRRELEVANT]" |
| 28 | + STATUS_OLD = "[OLD]" |
| 29 | + STATUS_CURRENT = "[CURRENT]" |
| 30 | + |
| 31 | + default_owner = firebase_github.OWNER |
| 32 | + default_repo = firebase_github.REPO |
| 33 | + |
| 34 | + parser = argparse.ArgumentParser( |
| 35 | + description="Fetch review comments from a GitHub PR and format into simple text output.", |
| 36 | + formatter_class=argparse.RawTextHelpFormatter |
| 37 | + ) |
| 38 | + parser.add_argument( |
| 39 | + "--pull_number", |
| 40 | + type=int, |
| 41 | + required=True, |
| 42 | + help="Pull request number." |
| 43 | + ) |
| 44 | + parser.add_argument( |
| 45 | + "--owner", |
| 46 | + type=str, |
| 47 | + default=default_owner, |
| 48 | + help=f"Repository owner. Defaults to '{default_owner}'." |
| 49 | + ) |
| 50 | + parser.add_argument( |
| 51 | + "--repo", |
| 52 | + type=str, |
| 53 | + default=default_repo, |
| 54 | + help=f"Repository name. Defaults to '{default_repo}'." |
| 55 | + ) |
| 56 | + parser.add_argument( |
| 57 | + "--token", |
| 58 | + type=str, |
| 59 | + default=os.environ.get("GITHUB_TOKEN"), |
| 60 | + help="GitHub token. Can also be set via GITHUB_TOKEN env var." |
| 61 | + ) |
| 62 | + parser.add_argument( |
| 63 | + "--context-lines", |
| 64 | + type=int, |
| 65 | + default=10, |
| 66 | + help="Number of context lines from the diff hunk. 0 for full hunk. If > 0, shows header (if any) and last N lines of the remaining hunk. Default: 10." |
| 67 | + ) |
| 68 | + parser.add_argument( |
| 69 | + "--since", |
| 70 | + type=str, |
| 71 | + default=None, |
| 72 | + help="Only show comments updated at or after this ISO 8601 timestamp (e.g., YYYY-MM-DDTHH:MM:SSZ)." |
| 73 | + ) |
| 74 | + parser.add_argument( |
| 75 | + "--exclude-old", |
| 76 | + action="store_true", |
| 77 | + default=False, |
| 78 | + help="Exclude comments marked [OLD] (where line number has changed due to code updates but position is still valid)." |
| 79 | + ) |
| 80 | + parser.add_argument( |
| 81 | + "--include-irrelevant", |
| 82 | + action="store_true", |
| 83 | + default=False, |
| 84 | + help="Include comments marked [IRRELEVANT] (where GitHub can no longer anchor the comment to the diff, i.e., position is null)." |
| 85 | + ) |
| 86 | + |
| 87 | + args = parser.parse_args() |
| 88 | + |
| 89 | + if not args.token: |
| 90 | + sys.stderr.write("Error: GitHub token not provided. Set GITHUB_TOKEN or use --token.\n") |
| 91 | + sys.exit(1) |
| 92 | + |
| 93 | + if args.owner != firebase_github.OWNER or args.repo != firebase_github.REPO: |
| 94 | + repo_url = f"https://github.com/{args.owner}/{args.repo}" |
| 95 | + if not firebase_github.set_repo_url(repo_url): |
| 96 | + sys.stderr.write(f"Error: Invalid repo URL: {args.owner}/{args.repo}. Expected https://github.com/owner/repo\n") |
| 97 | + sys.exit(1) |
| 98 | + sys.stderr.write(f"Targeting repository: {firebase_github.OWNER}/{firebase_github.REPO}\n") |
| 99 | + |
| 100 | + sys.stderr.write(f"Fetching comments for PR #{args.pull_number} from {firebase_github.OWNER}/{firebase_github.REPO}...\n") |
| 101 | + if args.since: |
| 102 | + sys.stderr.write(f"Filtering comments updated since: {args.since}\n") |
| 103 | + |
| 104 | + |
| 105 | + comments = firebase_github.get_pull_request_review_comments( |
| 106 | + args.token, |
| 107 | + args.pull_number, |
| 108 | + since=args.since |
| 109 | + ) |
| 110 | + |
| 111 | + if not comments: |
| 112 | + sys.stderr.write(f"No review comments found for PR #{args.pull_number} (or matching filters), or an error occurred.\n") |
| 113 | + return |
| 114 | + |
| 115 | + latest_activity_timestamp_obj = None |
| 116 | + processed_comments_count = 0 |
| 117 | + print("# Review Comments\n\n") |
| 118 | + for comment in comments: |
| 119 | + created_at_str = comment.get("created_at") |
| 120 | + |
| 121 | + current_pos = comment.get("position") |
| 122 | + current_line = comment.get("line") |
| 123 | + original_line = comment.get("original_line") |
| 124 | + |
| 125 | + status_text = "" |
| 126 | + line_to_display = None |
| 127 | + |
| 128 | + if current_pos is None: |
| 129 | + status_text = STATUS_IRRELEVANT |
| 130 | + line_to_display = original_line |
| 131 | + elif original_line is not None and current_line != original_line: |
| 132 | + status_text = STATUS_OLD |
| 133 | + line_to_display = current_line |
| 134 | + else: |
| 135 | + status_text = STATUS_CURRENT |
| 136 | + line_to_display = current_line |
| 137 | + |
| 138 | + if line_to_display is None: |
| 139 | + line_to_display = "N/A" |
| 140 | + |
| 141 | + if status_text == STATUS_IRRELEVANT and not args.include_irrelevant: |
| 142 | + continue |
| 143 | + if status_text == STATUS_OLD and args.exclude_old: |
| 144 | + continue |
| 145 | + |
| 146 | + # Track latest 'updated_at' for '--since' suggestion; 'created_at' is for display. |
| 147 | + updated_at_str = comment.get("updated_at") |
| 148 | + if updated_at_str: # Check if updated_at_str is not None and not empty |
| 149 | + try: |
| 150 | + if sys.version_info < (3, 11): |
| 151 | + dt_str_updated = updated_at_str.replace("Z", "+00:00") |
| 152 | + else: |
| 153 | + dt_str_updated = updated_at_str |
| 154 | + current_comment_activity_dt = datetime.datetime.fromisoformat(dt_str_updated) |
| 155 | + if latest_activity_timestamp_obj is None or current_comment_activity_dt > latest_activity_timestamp_obj: |
| 156 | + latest_activity_timestamp_obj = current_comment_activity_dt |
| 157 | + except ValueError: |
| 158 | + sys.stderr.write(f"Warning: Could not parse updated_at timestamp: {updated_at_str}\n") |
| 159 | + |
| 160 | + # Get other comment details |
| 161 | + user = comment.get("user", {}).get("login", "Unknown user") |
| 162 | + path = comment.get("path", "N/A") |
| 163 | + body = comment.get("body", "").strip() |
| 164 | + |
| 165 | + if not body: |
| 166 | + continue |
| 167 | + |
| 168 | + processed_comments_count += 1 |
| 169 | + |
| 170 | + diff_hunk = comment.get("diff_hunk") |
| 171 | + html_url = comment.get("html_url", "N/A") |
| 172 | + comment_id = comment.get("id") |
| 173 | + in_reply_to_id = comment.get("in_reply_to_id") |
| 174 | + |
| 175 | + print(f"## Comment by: **{user}** (ID: `{comment_id}`){f' (In Reply To: `{in_reply_to_id}`)' if in_reply_to_id else ''}\n") |
| 176 | + if created_at_str: |
| 177 | + print(f"* **Timestamp**: `{created_at_str}`") |
| 178 | + print(f"* **Status**: `{status_text}`") |
| 179 | + print(f"* **File**: `{path}`") |
| 180 | + print(f"* **Line**: `{line_to_display}`") |
| 181 | + print(f"* **URL**: <{html_url}>\n") |
| 182 | + |
| 183 | + print("\n### Context:") |
| 184 | + print("```") # Start of Markdown code block |
| 185 | + if diff_hunk and diff_hunk.strip(): |
| 186 | + if args.context_lines == 0: # User wants the full hunk |
| 187 | + print(diff_hunk) |
| 188 | + else: # User wants N lines of context (args.context_lines > 0) |
| 189 | + hunk_lines = diff_hunk.split('\n') |
| 190 | + if hunk_lines and hunk_lines[0].startswith("@@ "): |
| 191 | + print(hunk_lines[0]) |
| 192 | + hunk_lines = hunk_lines[1:] # Modify list in place for remaining operations |
| 193 | + |
| 194 | + # Proceed with the (potentially modified) hunk_lines |
| 195 | + # If hunk_lines is empty here (e.g. original hunk was only a header that was removed), |
| 196 | + # hunk_lines[-args.context_lines:] will be [], and "\n".join([]) is "", |
| 197 | + # so print("") will effectively print a newline. This is acceptable. |
| 198 | + print("\n".join(hunk_lines[-args.context_lines:])) |
| 199 | + else: # diff_hunk was None or empty |
| 200 | + print("(No diff hunk available for this comment)") |
| 201 | + print("```") # End of Markdown code block |
| 202 | + |
| 203 | + print("\n### Comment:") |
| 204 | + print(body) |
| 205 | + print("\n---") |
| 206 | + |
| 207 | + sys.stderr.write(f"\nPrinted {processed_comments_count} comments to stdout.\n") |
| 208 | + |
| 209 | + if latest_activity_timestamp_obj: |
| 210 | + try: |
| 211 | + # Ensure it's UTC before adding timedelta, then format |
| 212 | + next_since_dt = latest_activity_timestamp_obj.astimezone(timezone.utc) + timedelta(seconds=2) |
| 213 | + next_since_str = next_since_dt.strftime('%Y-%m-%dT%H:%M:%SZ') |
| 214 | + |
| 215 | + new_cmd_args = [sys.executable, sys.argv[0]] # Start with interpreter and script path |
| 216 | + i = 1 # Start checking from actual arguments in sys.argv |
| 217 | + while i < len(sys.argv): |
| 218 | + if sys.argv[i] == "--since": |
| 219 | + i += 2 # Skip --since and its value |
| 220 | + continue |
| 221 | + new_cmd_args.append(sys.argv[i]) |
| 222 | + i += 1 |
| 223 | + |
| 224 | + new_cmd_args.extend(["--since", next_since_str]) |
| 225 | + suggested_cmd = " ".join(new_cmd_args) |
| 226 | + sys.stderr.write(f"\nTo get comments created after the last one in this batch, try:\n{suggested_cmd}\n") |
| 227 | + except Exception as e: |
| 228 | + sys.stderr.write(f"\nWarning: Could not generate next command suggestion: {e}\n") |
| 229 | + |
| 230 | +if __name__ == "__main__": |
| 231 | + main() |
0 commit comments