header image

Code Snippets

Travis-CI GitHub PR Automerge

| Last updated:
#!/bin/bash -ev
# TravisCI Automerge PR Script

if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then
    >&2 echo 'Not in pull request, skipping automerge'
    exit 1

# Ensure all required environment variables are present
if [ -z "$TRAVIS_REPO_SLUG" ] || \
    [ -z "$TRAVIS_BRANCH" ] || \
    [ -z "$TRAVIS_PULL_REQUEST_SHA" ] || \
    [ -z "$GITHUB_SECRET_TOKEN" ] || \
    [ -z "$GIT_COMMITTER_EMAIL" ] || \
    [ -z "$GIT_COMMITTER_NAME" ]; then
    >&2 echo 'Required variable unset, automerging failed'
    exit 1

echo : "
Travis-ci automerge pull request script

# Checkout full repo
repo_temp=$(mktemp -d)
git clone "https://github.com/$TRAVIS_REPO_SLUG" "$repo_temp"
cd "$repo_temp"

printf 'Checking out %s\n' "$TRAVIS_BRANCH"
git checkout "$TRAVIS_BRANCH"

# Ensure PR commit is head of branch to be merged
branch_head_commit=$(git rev-parse HEAD)
if [ "$branch_head_commit" != "$TRAVIS_PULL_REQUEST_SHA" ]; then
    >&2 echo "Pull request commit ($TRAVIS_PULL_REQUEST_SHA) and does not match HEAD of branch to be merged ($branch_head_commit), automerge failed"
    exit 1

printf 'Merging %s\n' "$TRAVIS_PULL_REQUEST_BRANCH"

printf 'Pushing to %s\n' "$TRAVIS_REPO_SLUG"

# Push to github to complete merge
# Redirect to /dev/null to avoid secret leakage
git push "$push_uri" "$TRAVIS_BRANCH" >/dev/null 2>&1
git push "$push_uri" :"$TRAVIS_PULL_REQUEST_BRANCH" >/dev/null 2>&1

Automatically merge successful pull requests on TravisCI

Add to project in suitable scripts directory:


Then include under the after_success key in .travis.yml

- /scripts/travis-ci/travis-ci-automerge-script.sh

Generate a GitHub Personal Access Token in github.com/settings/tokens with public or private repo access.

Ensure correct environment variables are set in the build, either using Travis secure values or adding directly on travis-ci.com.


Note: when adding environment variables as Travis-CI secure values they will only be available in pull requests created by trusted users. Therefore, if an outside user makes a pull request to your repository, they will not have access to your access token and the pull request will not be merged.

Note: Depending on when your travis-ci account was made, secret may require encrypting with the --com flag. See this stackoverflow for more details.