Skip to content

Instantly share code, notes, and snippets.

@justinmakaila
Created August 27, 2019 17:36
Show Gist options
  • Save justinmakaila/2d56741b93a1756ef4931869ddae311f to your computer and use it in GitHub Desktop.
Save justinmakaila/2d56741b93a1756ef4931869ddae311f to your computer and use it in GitHub Desktop.
Detects the commit range of a PR on CircleCI since the last successful status check
# Build what's changed in the HEAD commit by default
COMMIT_RANGE="$CIRCLE_SHA1"
# If this is a PR, diff the changes over time against ther commit status
# according to the Github API.
# TODO: This should move to a Circle Orb cause OSS is sweet.
if ! [[ -z ${CIRCLE_PULL_REQUEST+x} ]];
then
GITHUB_USER=wellth-app
GITHUB_REPO_NAME=react-components
GITHUB_API_URI=https://api.github.com
GITHUB_REPO_PATH=$GITHUB_API_URI/repos/$GITHUB_USER/$GITHUB_REPO_NAME
GITHUB_AUTHORIZATION_HEADER="Authorization: token $GITHUB_API_TOKEN"
GITHUB_PR_NUMBER=${CIRCLE_PULL_REQUEST##*/}
# Hit the github API for PR commit range
# !!!: Accept header is to include draft pull requests.
GITHUB_PULL_REQUEST=$(curl -H "$GITHUB_AUTHORIZATION_HEADER" \
-H "Accept: application/vnd.github.shadow-cat-preview+json" \
$GITHUB_REPO_PATH/pulls/$GITHUB_PR_NUMBER)
BASE=$(echo $GITHUB_PULL_REQUEST | jq '.base.sha' | tr -d '"')
HEAD=$(echo $GITHUB_PULL_REQUEST | jq '.head.sha' | tr -d '"')
# Get the commits from BASE...HEAD, exclusive.
# `rev-list` exludes base from it's return value
# while adding `^` ensures we compare up to the commit
# before HEAD.
for commit in $(git rev-list $BASE...$HEAD^)
do
# Get the commit status from github
COMMIT_STATUS=$(curl -H "$GITHUB_AUTHORIZATION_HEADER" \
$GITHUB_REPO_PATH/commits/$commit/status | jq '.state')
if [ $COMMIT_STATUS == 'success' ];
then
BASE=$commit
continue
fi
done
COMMIT_RANGE="$BASE...$HEAD"
fi
echo "Building over commit range: $COMMIT_RANGE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment