Hello everyone!
If you are doing custom configuration with pull requests, you may run into a case where you need access to the name of the pull request’s base branch. Currently, this is not provided within a CircleCI build but is easily accessible through the GitHub API.
However, within PR builds, we have access to two extra environment variables called CIRCLE_PULL_REQUEST and CIRCLE_PULL_REQUESTS. The first is a link to the main pull request and the second is a list of pull request URLs. We only need CIRCLE_PULL_REQUEST - which we will transform into a GitHub API URL.
We need to mutate https://github.com/<org-name>/<project>/pull/<pr-number> to https://api.github.com/repos/<org-name>/<project>/pulls/<pr-number>. There are many ways this can be done, but we will trim the first 19 characters (https://github.com/) and append the result to https://api.github.com/repos/. After I run it through a sed substitution and replace /pull/ with /pulls/. This could theoretically cause an issue if your organization or project name is pull.
echo https://api.github.com/repos/${CIRCLE_PULL_REQUEST:19} | sed "s/\/pull\//\/pulls\//"
Set an environment variable called GITHUB_TOKEN with your GitHub authorization token. After which we can make the cURL request and retrieve the pull requests base name through jq:
curl -s -H "Authorization: token ${GITHUB_TOKEN}" $pr | jq '.base.ref'
Example usage:
version: 2.1
commands:
check-pr:
description: "Run API depending on branch"
parameters:
head:
type: string
base:
type: string
run:
type: string
steps:
- when:
condition:
equal: [ << parameters.head >>, << pipeline.git.branch >> ]
steps:
- run:
name: Check Pull Request from << parameters.head >> to << parameters.base >>
command: |
if [ -n $CIRCLE_PULL_REQUEST ]; then
pr=$(echo https://api.github.com/repos/${CIRCLE_PULL_REQUEST:19} | sed "s/\/pull\//\/pulls\//")
base=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" $pr | jq '.base.ref')
if [[ '"<< parameters.base >>"' = "$base" ]]; then
<< parameters.run >>
fi
fi
jobs:
test-dev:
docker:
- image: circleci/node:latest
steps:
- check-pr:
base: staging
head: dev
run: |
echo "hello world!"
# implement features here!
workflows:
test:
jobs:
- test-dev:
Limitations:
- Ensure that your image has
jqinstalled. - If you are trying to catch when a pull request is opened, you must have the
Only build pull requests
feature enabled. If you have this disabled, opening a new pull request will not trigger a new build, because that commit has already been completed.