import os import sys import re import json import requests platform = os.environ.get("PLATFORM", "github").lower() token = os.environ["TOKEN"] owner = os.environ["REPO_OWNER"] repo = os.environ["REPO_NAME"] pr_index = os.environ["PR_INDEX"] api_url = os.environ.get("API_URL") diff_text = os.environ.get("DIFF") comment_template = os.environ.get("COMMENT_TEMPLATE", "") if not diff_text: print("No diff provided", file=sys.stderr) sys.exit(1) # Parse diff diff_files = {} current_file = None new_line_num = None for line in diff_text.splitlines(): if line.startswith("+++ b/"): current_file = line[6:].strip() diff_files[current_file] = [] new_line_num = 0 elif line.startswith("@@"): m = re.match(r"@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line) if m: new_line_num = int(m.group(1)) - 1 elif line.startswith("+") and not line.startswith("+++"): new_line_num += 1 content = line[1:] diff_files[current_file].append((new_line_num, content)) elif not line.startswith("-"): new_line_num += 1 # Post comments for file_path, lines in diff_files.items(): if not lines: continue all_lines_content = "\n".join([line_content for _, line_content in lines]) for line_number, line_content in lines: body = comment_template.replace("{line}", line_content).replace("{lines}", all_lines_content) if platform == "github": url = f"https://api.github.com/repos/{owner}/{repo}/issues/{pr_index}/comments" payload = {"body": body} if file_path and line_number: url = f"https://api.github.com/repos/{owner}/{repo}/pulls/{pr_index}/comments" payload.update({ "body": body, "path": file_path, "position": line_number }) elif platform == "gitea": if not api_url: print("Gitea API URL required", file=sys.stderr) sys.exit(1) url = f"{api_url}/repos/{owner}/{repo}/pulls/{pr_index}/comments" payload = {"body": body} if file_path and line_number: payload.update({ "path": file_path, "position": line_number }) else: print(f"Unsupported platform: {platform}", file=sys.stderr) sys.exit(1) headers = { "Authorization": f"token {token}", "Content-Type": "application/json", } resp = requests.post(url, headers=headers, json=payload) if resp.status_code in (201, 200): print(f"Comment posted on {file_path}:{line_number}") else: print(f"Failed to post comment on {file_path}:{line_number} ({resp.status_code})", file=sys.stderr) print(resp.text, file=sys.stderr)