Created
March 5, 2024 06:22
-
-
Save shivanshs9/1174407300509fb35d6914bd6ddd6b27 to your computer and use it in GitHub Desktop.
Approve/Raise/Check a Github PR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
# Function to display help | |
display_help() { | |
echo "Usage: $0 [command] [args]" | |
echo "Command:" | |
echo " approve Approves the specified PR in format of URL" | |
echo " create Creates a new PR from specified args" | |
echo "Options:" | |
echo " -t, --token TOKEN Use provided github token for API authentication" | |
echo " -h, --help Display this help message" | |
echo " -b, --batch Do Batch processing with input file" | |
exit 1 | |
} | |
get_pr() { | |
org="$1" | |
repo="$2" | |
pr="$3" | |
curl_response=$(curl -X GET "https://api.github.com/repos/$org/$repo/pulls/$pr_number" \ | |
-H "Authorization: token $github_token" \ | |
-H "Content-Type: application/json" 2>/dev/null) | |
echo "$curl_response" | |
} | |
approve_pr() { | |
org_repo_pr=$(echo "$1" | awk -F'/' '{print $4,$5,$7}' OFS=' ') | |
# Splitting the result into variables | |
read -r org repo pr_number <<< "$org_repo_pr" | |
echo "Approving PR #$pr_number for $org/$repo..." | |
pr_mergeable=$(get_pr $org $repo $pr_number | jq '.mergeable') | |
if [[ "$pr_mergeable" = "false" ]]; then | |
echo "=> Merge conflicts detected! Can't be merged" | |
exit 1 | |
fi | |
data=$(jq -cn '.event = "APPROVE"') | |
# Call GitHub API to create a PR review | |
curl_response=$(curl -X POST "https://api.github.com/repos/$org/$repo/pulls/$pr_number/reviews" \ | |
-H "Authorization: token $github_token" \ | |
-H "Content-Type: application/json" \ | |
-d "$data" 2>/dev/null) | |
# echo "$curl_response" | jq '.' | |
# Check if the request was successful (status code 2xx) | |
if [[ $(echo "$curl_response" | grep -c "\"message\": \"") -gt 0 ]]; then | |
echo "Error approving PR: $curl_response" | |
exit 1 | |
else | |
echo "=> Done!" | |
fi | |
} | |
raise_pr() { | |
exit 0 | |
} | |
batch=false | |
# # Parse command-line options | |
while [[ "$#" -gt 0 ]]; do | |
case $1 in | |
-t|--token) | |
github_token="$2" | |
shift | |
;; | |
-h|--help) | |
display_help | |
exit 0 | |
;; | |
-b|--batch) | |
batch=true | |
;; | |
*) | |
ARGS+=("$1") | |
;; | |
esac | |
shift | |
done | |
set -- "${ARGS[@]}" | |
cmd="$1" | |
shift | |
case "$cmd" in | |
approve) | |
approve_pr "$1" | |
;; | |
create) | |
raise_pr "$1" "$2" "$3" "$4" | |
;; | |
*) | |
display_help | |
exit 1 | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment