Skip to content

Instantly share code, notes, and snippets.

@SurajAdsul
Last active March 25, 2025 00:21
Show Gist options
  • Save SurajAdsul/66a594b951a841c3ede07e2e6715c418 to your computer and use it in GitHub Desktop.
Save SurajAdsul/66a594b951a841c3ede07e2e6715c418 to your computer and use it in GitHub Desktop.
import re
import subprocess
import argparse
def get_repo():
"""Fetches the GitHub repository details from the current branch."""
result = subprocess.run("git config --get remote.origin.url", shell=True, capture_output=True, text=True)
if result.returncode != 0:
print("Error fetching repository details:", result.stderr)
exit(1)
repo_url = result.stdout.strip()
repo = repo_url.split(':')[-1].replace('.git', '').replace('/', '/')
return repo
def get_pr_number():
"""Fetches the current PR number if available."""
result = subprocess.run("gh pr view --json number --jq .number", shell=True, capture_output=True, text=True)
if result.returncode != 0:
print("Error fetching PR number. Ensure you are on a PR branch:", result.stderr)
exit(1)
return result.stdout.strip()
def get_pr_diff(pr_number, repo):
"""Fetches the PR diff using GitHub CLI."""
cmd = f"gh pr diff {pr_number} --repo {repo}"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode != 0:
print("Error fetching PR diff:", result.stderr)
exit(1)
return result.stdout
def parse_diff(diff_text):
result = []
current_file = None
current_hunk = None
for line in diff_text.splitlines():
file_match = re.match(r'^diff --git a/(.+) b/(.+)', line)
if file_match:
if current_file:
result.append("\n".join(current_file))
current_file = [f"## File: '{file_match.group(2)}'"]
current_hunk = None # Reset current hunk when a new file starts
continue
hunk_match = re.match(r'^@@.*@@', line)
if hunk_match:
if current_hunk:
result.append("\n".join(current_hunk))
current_hunk = ["\n@@ ... @@", "__new hunk__"]
continue
if current_hunk is None:
current_hunk = [] # Ensure hunk is initialized
if line.startswith('+') and not line.startswith('+++'):
current_hunk.append(f"{line[1:]} +new code line added in the PR")
elif line.startswith('-') and not line.startswith('---'):
current_hunk.append(f"{line[1:]} -old code line removed in the PR")
else:
current_hunk.append(line)
if current_hunk:
result.append("\n".join(current_hunk))
if current_file:
result.append("\n".join(current_file))
return "\n".join(result)
if __name__ == "__main__":
repo = get_repo()
pr_number = get_pr_number()
diff_content = get_pr_diff(pr_number, repo)
parsed_diff = parse_diff(diff_content)
print(parsed_diff)
#!/bin/bash
export GITHUB_TOKEN="Add your token here"
# Ensure required environment variables are set
if [ -z "$GITHUB_TOKEN" ]; then
echo "Error: GITHUB_TOKEN environment variable is not set."
exit 1
fi
# Check arguments
if [ "$1" != "pr" ] || [ "$2" != "review" ]; then
echo "Usage: $0 pr review <PR_NUMBER> --comment -b <review comment> --path <FILE_PATH> --line <LINE_NUMBER>"
exit 1
fi
# Parse arguments
PR_NUMBER=$3
shift 3
COMMENT=""
FILE_PATH=""
LINE_NUMBER=""
while [[ $# -gt 0 ]]; do
case "$1" in
--comment)
shift
if [ "$1" != "-b" ]; then
echo "Error: --comment flag must be followed by -b <review comment>"
exit 1
fi
shift
COMMENT="$1"
;;
--path)
shift
FILE_PATH="$1"
;;
--line)
shift
LINE_NUMBER="$1"
;;
*)
echo "Unknown argument: $1"
exit 1
;;
esac
shift
done
# Validate required parameters
if [ -z "$PR_NUMBER" ] || [ -z "$COMMENT" ] || [ -z "$FILE_PATH" ] || [ -z "$LINE_NUMBER" ]; then
echo "Error: Missing required parameters."
echo "Usage: $0 pr review <PR_NUMBER> --comment -b <review comment> --path <FILE_PATH> --line <LINE_NUMBER>"
exit 1
fi
# Get repository owner and name from git remote
REMOTE_URL=$(git config --get remote.origin.url)
if [[ "$REMOTE_URL" =~ github.com[:/]([^/]+)/([^/.]+) ]]; then
OWNER="${BASH_REMATCH[1]}"
REPO="${BASH_REMATCH[2]}"
else
echo "Error: Could not determine repository owner and name from remote URL: $REMOTE_URL"
exit 1
fi
echo "Repository: $OWNER/$REPO"
echo "PR Number: $PR_NUMBER"
echo "File Path: $FILE_PATH"
echo "Line Number: $LINE_NUMBER"
echo "Comment: $COMMENT"
echo "Fetching commit ID..."
# Get latest commit ID of the PR
API_COMMIT_URL="https://api.github.com/repos/$OWNER/$REPO/pulls/$PR_NUMBER"
LATEST_COMMIT_ID=$(curl -s -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3+json" "$API_COMMIT_URL" | jq -r '.head.sha')
if [ -z "$LATEST_COMMIT_ID" ] || [ "$LATEST_COMMIT_ID" == "null" ]; then
echo "Error: Could not fetch the latest commit ID for PR #$PR_NUMBER"
exit 1
fi
echo "Latest Commit ID: $LATEST_COMMIT_ID"
# Add review comment using GitHub API
API_URL="https://api.github.com/repos/$OWNER/$REPO/pulls/$PR_NUMBER/comments"
RESPONSE=$(curl -L -s -o response.json -w "%{http_code}" \
-X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GITHUB_TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
"$API_URL" \
-d "{
\"body\": \"$COMMENT\",
\"commit_id\": \"$LATEST_COMMIT_ID\",
\"path\": \"$FILE_PATH\",
\"line\": $LINE_NUMBER,
\"side\": \"RIGHT\"
}")
# cat response.json
# echo "Response Code: $RESPONSE"
if [[ "$RESPONSE" -ne 201 ]]; then
echo "Failed to add review comment. Check response.json for more details."
exit 1
fi
echo "Review comment added successfully."
# Github PR review
You are an experienced senior software engineer tasked with reviewing a Git Pull Request (PR). Your goal is to provide comments to improve code quality, catch typos, potential bugs or security issues, and provide meaningful code suggestions when applicable. You should not make comments about adding comments, about code formatting, about code style or give implementation suggestions.
The review should focus on new code added in the PR code diff (lines starting with '+') and be actionable.
The PR diff will have the following structure:
======
## File: 'src/file1.py'
@@ ... @@ def func1():
__new hunk__
11 unchanged code line0 in the PR
12 unchanged code line1 in the PR
13 +new code line2 added in the PR
14 unchanged code line3 in the PR
__old hunk__
unchanged code line0
unchanged code line1
-old code line2 removed in the PR
unchanged code line3
__existing_comment_thread__
presubmitai: This is a comment on the code
user2: This is a reply to the comment above
__existing_comment_thread__
presubmitai: This is a comment on some other parts of the code
user2: This is a reply to the above comment
@@ ... @@ def func2():
__new hunk__
unchanged code line4
+new code line5 removed in the PR
unchanged code line6
## File: 'src/file2.py'
...
======
- In the format above, the diff is organized into separate '__new hunk__' and '__old hunk__' sections for each code chunk. '__new hunk__' contains the updated code, while '__old hunk__' shows the removed code. If no code was removed in a specific chunk, the __old hunk__ section will be omitted.
- We also added line numbers for the '__new hunk__' code, to help you refer to the code lines in your suggestions. These line numbers are not part of the actual code, and should only used for reference.
- Code lines are prefixed with symbols ('+', '-', ' '). The '+' symbol indicates new code added in the PR, the '-' symbol indicates code removed in the PR, and the ' ' symbol indicates unchanged code. The review should address new code added in the PR code diff (lines starting with '+')
- Use markdown formatting for your comments.
- Do not return comments that are even slightly similar to other existing comments for the same hunk diffs.
- If you cannot find any actionable comments, return an empty array.
- VERY IMPORTANT: Keep in mind you're only seeing part of the code, and the code might be incomplete. Do not make assumptions about the code outside the diff.
- Do not give positive comments or compliments.
- Use fetch_pr_diff tool first to review the code and then generate the JSON response in following JSON format: {"reviews": [{"filePath": <file_path>, "lineNumber": <line_number>, "reviewComment": "<review comment>"}]}
## Tools
You can utilize these tools.
- GitHub CLI
```bash
# cd aaisp-frontend && gh pr diff <PR_NUMBER> | grep "^+" | cat
# cd aaisp-frontend && gh pr diff <PR_NUMBER> | cat
cd aaisp-frontend && python3 ../tools/fetch_pr_diff.py
```
Use the json from given Prompt to comment on PR. Use command like this for each review comment like this.
```bash
cd aaisp-frontend && ../tools/gh-pr-comment.sh pr review <PR_NUMBER> --comment -b <review comment> --path <FILE_PATH> --line <LINE_NUMBER>
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment