Bitbucket pipeline - possibility to merge one branch to another

I was facing the same issue, but wanted to use pull requests instead of simple git merge. So I ended up utilising bitbucket API for the job:

1. Create "App password"

Create "App password" so you don't have to push your own credentials to pipelines (bitbucket settings -> app passwords)

bitbucket app password

2. Set environment variables for pipelines

  • BB_USER = your username
  • BB_PASSWORD = app password

3. Create bash script

I have a bash script that creates pull request from $BITBUCKET_BRANCH and merge it immediately

#!/usr/bin/env bash

# Exit immediately if a any command exits with a non-zero status
# e.g. pull-request merge fails because of conflict
set -e

# Set destination branch
DEST_BRANCH=$1

# Create new pull request and get its ID
echo "Creating PR: $BITBUCKET_BRANCH -> $DEST_BRANCH"
PR_ID=`curl -X POST https://api.bitbucket.org/2.0/repositories/$BITBUCKET_REPO_OWNER/$BITBUCKET_REPO_SLUG/pullrequests \
  --fail --show-error --silent \
  --user $BB_USER:$BB_PASSWORD \
  -H 'content-type: application/json' \
  -d '{
    "title": "'$BITBUCKET_BRANCH' -> '$DEST_BRANCH'",
    "description": "automatic PR from pipelines",
    "state": "OPEN",
    "destination": {
      "branch": {
              "name": "'$DEST_BRANCH'"
          }
    },
    "source": {
      "branch": {
              "name": "'$BITBUCKET_BRANCH'"
          }
    }
  }' \
  | sed -E "s/.*\"id\": ([0-9]+).*/\1/g"`

# Merge PR
echo "Merging PR: $PR_ID"
curl -X POST https://api.bitbucket.org/2.0/repositories/$BITBUCKET_REPO_OWNER/$BITBUCKET_REPO_SLUG/pullrequests/$PR_ID/merge \
  --fail --show-error --silent \
  --user $BB_USER:$BB_PASSWORD \
  -H 'content-type: application/json' \
  -d '{
    "close_source_branch": false,
    "merge_strategy": "merge_commit"
  }'
  • usage: ./merge.sh DESTINATION_BRANCH
  • see pipelines environment variables documentation to understand better used variables
  • see bitbucket API docs for more info about used API

4. Finally in pipelines

just call the script:

Dev:
       - step:
           script:
            - ./merge.sh master

Benefits:

  • Pipeline will fail if there is conflict (if you want it to fail)
  • better control of what's happening