Skip to content

Instantly share code, notes, and snippets.

@ip1981
Last active Apr 22, 2017
Embed
What would you like to do?
#!/usr/bin/env bash
set -euo pipefail
ME=''
GITHUB_API_TOKEN=${GITHUB_API_TOKEN:-}
ACTION=false
CURL=${CURL:-curl}
JQ=${JQ:-jq}
usage()
{
cat <<USAGE
Approve pull requests at Github in given repositories.
Usage: '$0' [options] owner1/repo1 [owner2/repo2 ...]
Options are:
-m "me", my Github login. Will not approve PR created by this user.
-a Action! Default is dry-run, i. e. don't really approve.
-h, -? This help message
Environment variables:
GITHUB_API_TOKEN - exactly what it reads. Required.
USAGE
exit 42
}
while getopts h?m:a opt; do
case $opt in
m) ME=$OPTARG;;
a) ACTION=true;;
*) usage;;
esac
done
shift $((OPTIND - 1))
REPOS=( "$@" )
_request()
{
$CURL -s -S -f \
-H "Authorization: token $GITHUB_API_TOKEN" \
-H 'Accept: application/vnd.github.black-cat-preview+json' \
"$@"
}
_POST()
{
_request -X POST \
-H 'Content-Type: application/json' \
"$@"
}
_GET()
{
_request -X GET \
"$@"
}
_approve()
{
local repo="$1"
local pr="$2"
# shellcheck disable=SC2016
_POST \
-d '{"event":"APPROVE", "body":"`¯\\_(ツ)_/¯`"}' \
"https://api.github.com/repos/$repo/pulls/$pr/reviews"
}
_isApproved()
{
local repo="$1"
local pr="$2"
_GET \
"https://api.github.com/repos/$repo/pulls/$pr/reviews" \
| $JQ -e '. | map(select(.state == "APPROVED")) | length > 0' >/dev/null
}
approve()
{
local repo="$1"
local pr="$2"
if _isApproved "$repo" "$pr"; then
echo "PR $pr in $repo is already approved" >&2
else
if $ACTION; then
echo "Approving PR $pr in $repo" >&2
_approve "$repo" "$pr" | $JQ -r '. | .pull_request_url'
else
echo "Would approve PR $pr in $repo" >&2
fi
fi
}
listPullRequests()
{
local repo="$1"
_GET \
"https://api.github.com/repos/$repo/pulls?state=open&base=master" \
| $JQ ". | map(select(.user.login != \"$ME\")) | .[] | .number"
}
for repo in "${REPOS[@]}"; do
listPullRequests "$repo" \
| while read -r pr; do
echo "Checking PR $pr in $repo" >&2
approve "$repo" "$pr"
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment