Skip to content

Instantly share code, notes, and snippets.

@sjones6
Created August 2, 2018 19:34
Show Gist options
  • Save sjones6/396d301543eb026992728cd380344c06 to your computer and use it in GitHub Desktop.
Save sjones6/396d301543eb026992728cd380344c06 to your computer and use it in GitHub Desktop.
How to Merge Target Branch in CircleCI Job

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

@tomjohnburton
Copy link

Small update:

You now need to move the supply the GITHUB_TOKEN as a header

          target_branch=$(
          curl -H "Authorization: token $GITHUB_TOKEN" "$url" | jq '.base.ref' | tr -d '"'
          )```

@joykuotw
Copy link

joykuotw commented Nov 25, 2021

Suggest making the set value of git config quoted, or the command will fail if the author name contains multiple spaces.

git config --global user.email '$( git log --format='%ae' $CIRCLE_SHA1^! )'
git config --global user.name '$( git log --format='%an' $CIRCLE_SHA1^! )'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment