Files
git-auto-comment/git-auto-comment.py
T
Trez.One 93ad50b386
Renovate / renovate (push) Successful in 2m34s
requirements.txt
2025-10-22 07:45:43 -04:00

86 lines
2.9 KiB
Python
Executable File

#!/usr/bin/env python3
import os
import sys
import re
import json
# --- Check for required dependency ---
try:
import requests
except ImportError:
print(
"❌ The 'requests' library is not installed.\n"
"Please ensure it's available in your runner.\n"
"If using a composite action, add:\n"
" - name: Install Python dependencies\n"
" run: |\n"
" python3 -m pip install --upgrade pip\n"
" python3 -m pip install requests",
file=sys.stderr,
)
sys.exit(1)
# --- Read environment variables ---
platform = os.environ.get("PLATFORM", "github").lower()
token = os.environ.get("TOKEN")
owner = os.environ.get("REPO_OWNER", os.environ.get("GITHUB_REPOSITORY_OWNER"))
repo = os.environ.get("REPO_NAME", os.environ.get("GITHUB_REPOSITORY"))
pr_index = os.environ.get("PR_INDEX")
api_url = os.environ.get("API_URL", os.environ.get("GITHUB_API_URL"))
plan_file = os.environ.get("PLAN_FILE")
diff_text = os.environ.get("DIFF") # still supported for legacy usage
comment_template = os.environ.get("COMMENT_TEMPLATE", "Auto-comment: changed line -> {line}")
if not token or not pr_index:
print("❌ TOKEN and PR_INDEX are required.", file=sys.stderr)
sys.exit(1)
# --- Load content from file or environment ---
content_text = None
if plan_file and os.path.exists(plan_file):
try:
with open(plan_file, "r", encoding="utf-8") as f:
content_text = f.read()
except Exception as e:
print(f"⚠️ Failed to read file '{plan_file}': {e}", file=sys.stderr)
sys.exit(1)
elif diff_text:
content_text = diff_text
# --- Prepare comment body ---
if not content_text:
body = comment_template.replace("{line}", "").replace("{lines}", "")
else:
body = comment_template.replace("{lines}", content_text).replace("{line}", "")
# --- Determine API endpoint ---
if platform == "github":
url = f"https://api.github.com/repos/{owner}/{repo}/issues/{pr_index}/comments"
elif platform == "gitea":
if not api_url:
print("❌ Gitea API URL required for Gitea platform", file=sys.stderr)
sys.exit(1)
url = f"{api_url}/repos/{owner}/{repo}/pulls/{pr_index}/comments"
else:
print(f"❌ Unsupported platform: {platform}", file=sys.stderr)
sys.exit(1)
# --- Post the comment ---
headers = {"Authorization": f"token {token}", "Content-Type": "application/json"}
payload = {"body": body}
print(f"🛰️ Posting comment to {platform.upper()} PR #{pr_index}...")
try:
resp = requests.post(url, headers=headers, json=payload)
if resp.status_code in (200, 201):
print("✅ Comment posted successfully!")
sys.exit(0)
else:
print(f"❌ Failed to post comment: {resp.status_code}", file=sys.stderr)
print(resp.text, file=sys.stderr)
sys.exit(1)
except requests.exceptions.RequestException as e:
print(f"❌ Network or API error: {e}", file=sys.stderr)
sys.exit(1)