Problem statement: you want to make sure that the PR branch is up-to-date with the target branch before running your CI job against it.
As a secondary concern, you don't want to run the job if there are conflicts with the target branch.
Solution:
# setup the github user
git config --global user.email $( git log --format='%ae' $CIRCLE_SHA1^! )
git config --global user.name $( git log --format='%an' $CIRCLE_SHA1^! )
# if this is a PR, we extract the API URL to grab the PR as JSON from the Github API
if [[ -n "$CIRCLE_PULL_REQUEST" ]]; then
url="$(echo "$CIRCLE_PULL_REQUEST" | sed 's/https:\/\/github.com\//https:\/\/api.github.com\/repos\//' | sed 's/\/pull\//\/pulls\//')?access_token=$GITHUB_TOKEN"
target_branch=$(
curl "$url" | jq '.base.ref' | tr -d '"'
)
echo "$target_branch"
# this will fail if $target_branch is null
# if it should pass, wrap this in `if [[ -n "$target_branch" ]]; then`
git fetch && git merge origin/$target_branch --no-edit
fi
Setup:
Make sure that a Github token that enables access to the repository is available as an build environment variable called GITHUB_TOKEN
You'll need jq
to parse the JSON returned from the Github api. You can use a Docker container that ships with that utility or run this before the above script:
sudo apt-get update
sudo apt-get install jq
For non-Debian distributions of Linux, use the appropriate package manager (not apt-get
Small update:
You now need to move the supply the GITHUB_TOKEN as a header