about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@fakecake.org>2026-06-22 17:25:36 +0300
committerAndrew Dolgov <fox@fakecake.org>2026-06-22 17:25:36 +0300
commit1e9f0276bc299a1c26ba329a4cc3b47e11448cf9 (patch)
tree0722ca09ba95237652cf0ec66cd8152dc2c7ea42
parent9fbcbede3f275801d97b5b2852750a72b277b7f3 (diff)
downloadthe-epube-1e9f0276bc299a1c26ba329a4cc3b47e11448cf9.tar.gz
the-epube-1e9f0276bc299a1c26ba329a4cc3b47e11448cf9.tar.xz
python version
-rw-r--r--.gitlab-ci.yml2
-rw-r--r--review_mr.py89
-rw-r--r--review_mr.sh39
3 files changed, 90 insertions, 40 deletions
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 8965794..cf83e28 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -195,4 +195,4 @@ mr-review:
   rules:
     - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $MR_REVIEW_TOKEN != null
   script:
-    - sh ./review_mr.sh
+    - python3 ./review_mr.py
diff --git a/review_mr.py b/review_mr.py
new file mode 100644
index 0000000..f31398a
--- /dev/null
+++ b/review_mr.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+"""GitLab MR Review Bot — fetches diff, sends to LLM, posts review comment."""
+
+import json
+import os
+import sys
+import requests
+
+
+def get_env(name: str) -> str:
+    """Get required environment variable, exit if missing."""
+    value = os.environ.get(name)
+    if not value:
+        print(f"Error: {name} is not set", file=sys.stderr)
+        sys.exit(1)
+    return value
+
+
+def fetch_diff(project_id: str, mr_iid: str, token: str, server_url: str) -> str:
+    """Fetch the MR diff and return formatted diff text."""
+    url = f"{server_url}/api/v4/projects/{project_id}/merge_requests/{mr_iid}/diffs"
+    resp = requests.get(url, headers={"PRIVATE-TOKEN": token})
+    resp.raise_for_status()
+    diffs = resp.json()
+    diff_text = "\n".join(d.get("diff", "") for d in diffs if d.get("diff"))
+    return diff_text[:10000]
+
+
+def send_to_llm(diff_text: str, endpoint: str, apikey: str) -> str:
+    """Send diff to LLM and return the review text."""
+    prompt = (
+        "Review the following code diff for potential bugs, security issues, "
+        "or improvements. Provide concise feedback in markdown format:\n\n"
+        f"{diff_text}"
+    )
+    payload = {
+        "messages": [{"role": "user", "content": prompt}],
+        "max_tokens": 1024,
+        "chat_template_kwargs": {"enable_thinking": False},
+    }
+    resp = requests.post(
+        f"{endpoint}/chat/completions",
+        headers={
+            "Content-Type": "application/json",
+            "Authorization": f"Bearer {apikey}",
+        },
+        json=payload,
+    )
+    resp.raise_for_status()
+    data = resp.json()
+    return data["choices"][0]["message"]["content"]
+
+
+def post_comment(project_id: str, mr_iid: str, token: str, server_url: str, body: str) -> None:
+    """Post the review comment to the MR."""
+    url = f"{server_url}/api/v4/projects/{project_id}/merge_requests/{mr_iid}/notes"
+    payload = {"body": f"### AI Code Review Summary\n\n{body}"}
+    resp = requests.post(
+        url,
+        headers={"PRIVATE-TOKEN": token, "Content-Type": "application/json"},
+        json=payload,
+    )
+    resp.raise_for_status()
+    print("Review comment posted successfully.")
+
+
+def main() -> None:
+    server_url = get_env("CI_SERVER_URL")
+    project_id = get_env("CI_PROJECT_ID")
+    mr_iid = get_env("CI_MERGE_REQUEST_IID")
+    token = get_env("MR_REVIEW_TOKEN")
+    endpoint = get_env("MR_REVIEW_ENDPOINT")
+    apikey = get_env("MR_REVIEW_APIKEY")
+
+    print("Fetching MR diff...")
+    diff_text = fetch_diff(project_id, mr_iid, token, server_url)
+    if not diff_text.strip():
+        print("No diff found. Exiting.", file=sys.stderr)
+        sys.exit(1)
+
+    print("Sending to LLM...")
+    review = send_to_llm(diff_text, endpoint, apikey)
+
+    print("Posting review comment...")
+    post_comment(project_id, mr_iid, token, server_url, review)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/review_mr.sh b/review_mr.sh
deleted file mode 100644
index 4343dae..0000000
--- a/review_mr.sh
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/usr/bin/env bash
-#set -e
-
-# 1. Fetch the diff for the current Merge Request
-API_URL="${CI_SERVER_URL}/api/v4/projects/${CI_PROJECT_ID}/merge_requests/${CI_MERGE_REQUEST_IID}/diffs"
-RESPONSE_FILE="diff.json"
-
-curl --header "PRIVATE-TOKEN: ${MR_REVIEW_TOKEN}" "${API_URL}" -o "${RESPONSE_FILE}"
-
-# 2. Extract and format the diff (truncating if it exceeds the model's context)
-# You may need to refine this to loop through files depending on LLM constraints
-DIFF_CONTENT=$(jq -r 'map(.diff) | join("\n")' "${RESPONSE_FILE}" | head -c 10000)
-
-# 3. Send to your OpenAI-compatible endpoint
-PAYLOAD=$(jq -n \
-  --arg prompt "Review the following code diff for potential bugs, security issues, or improvements. Provide concise feedback in markdown format:\n\n${DIFF_CONTENT}" \
-  '{messages: [{role: "user", content: $prompt}], max_tokens: 1024, chat_template_kwargs: {enable_thinking: false }}')
-
-echo $PAYLOAD
-
-LLM_RESPONSE=$(curl -s -X POST "${MR_REVIEW_ENDPOINT}/chat/completions" \
-  -H "Content-Type: application/json" \
-  -H "Authorization: Bearer ${MR_REVIEW_APIKEY}" \
-  -d "$PAYLOAD")
-
-echo ${LLM_RESPONSE}
-
-COMMENT_BODY=$(echo "$LLM_RESPONSE" | jq -r '.choices[0].message.content')
-
-# 4. Post the review comment back to the Merge Request
-COMMENT_URL="${CI_SERVER_URL}/api/v4/projects/${CI_PROJECT_ID}/merge_requests/${CI_MERGE_REQUEST_IID}/notes"
-
-COMMENT_JSON=$(jq -n --arg body "$COMMENT_BODY" '{body: ("### AI Code Review Summary\n\n" + $body)}')
-
-curl --header "PRIVATE-TOKEN: ${MR_REVIEW_TOKEN}" \
-     --header "Content-Type: application/json" \
-     --request POST \
-     --data "$COMMENT_JSON" \
-     "${COMMENT_URL}"