How to get the branch that the PR is heading to in CircleCI
Asked Answered
P

2

8

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.

Pedagogy answered 13/3, 2019 at 20:28 Comment(0)
J
3

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" )'
Juggle answered 15/4, 2022 at 6:51 Comment(0)
V
2

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:

  1. Create a GitHub personal access token using the repo scope
  2. Set a project environment variable called GITHUB_ACCESS_TOKEN
  3. Retrieve the pull request data in JSON format
  4. 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']")
Viridis answered 18/3, 2019 at 12:51 Comment(1)
The question does not mention GitHub at all. This could be a Bitbucket or GitLab question for all we know and it's incorrect to assume and provide specific answers for GitHub exclusively.Selah

© 2022 - 2024 — McMap. All rights reserved.