'How to get the branch that the PR is heading to in CircleCI
CircleCI have a CIRCLE_BRANCH
env variable that tells you the name of the branch of the PR itself.
But I want the other way around, I need the branch name of the PR is trying to merge against.
Solution 1:[1]
There's no built-in environment variable (see full list here) to get the name of the base branch of a pull request. You could however get the pull request number using the CIRCLE_PR_NUMBER
environment variable and use the GitHub REST API to retrieve the base branch name.
You're going to need to:
- Create a GitHub personal access token using the
repo
scope - Set a project environment variable called
GITHUB_ACCESS_TOKEN
- Retrieve the pull request data in JSON format
- Parse the JSON to get the base branch ref - there's a few ways to achieve that
Here's a sample bash script that retrieves a given pull request's data in JSON format and parses it using Python 2:
#!/bin/bash
REPO_OWNER="replace_me"
GITHUB_API_URL="https://api.github.com/repos/$REPO_OWNER/$CIRCLE_PROJECT_REPONAME/pulls/$CIRCLE_PR_NUMBER?access_token=$GITHUB_ACCESS_TOKEN"
export PYTHONIOENCODING=utf8
export PULL_REQUEST_BASE_REF=$(curl -s "$GITHUB_API_URL" | python -c "import sys, json; print json.load(sys.stdin)['base']['ref']")
Solution 2:[2]
You can simply set that by using github api and set the parameters tag for it to reuse same value under step runs.
parameters:
target-branch:
type: string
default: '$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" $(echo https://api.github.com/repos/${CIRCLE_PULL_REQUEST:19} | sed "s/\/pull\//\/pulls\//") | jq ".base.ref" | tr -d "\042" )'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Raju Muke |