Skip to content

Instantly share code, notes, and snippets.

@ccampo133
Last active July 10, 2020 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccampo133/757278269c9271946b16e311cdb095da to your computer and use it in GitHub Desktop.
Save ccampo133/757278269c9271946b16e311cdb095da to your computer and use it in GitHub Desktop.
Script to create Bitbucket Cloud PR
#!/usr/bin/env sh
# Create a Bitbucket Cloud PR from the command line. Expects the following
# environment variables:
# * BITBUCKET_CLIENT_ID
# * BITBUCKET_CLIENT_SECRET
#
# These can be obtained by creating a Bitbucket "OAuth Consumer". See:
# https://support.atlassian.com/bitbucket-cloud/docs/use-oauth-on-bitbucket-cloud
#
# Usage:
# ./bbpr [pr-title]
#
# If the title is not specified, it defaults to the branch name.
#
# NOTE: replace 'pbcopy' with the relevant command if not using MacOS.
#
# Requires: curl, jq
# Get branch name and PR title
branch=$(git rev-parse --abbrev-ref HEAD)
if [ -z "$title" ]; then
title="$branch"
fi
repo=$(git remote get-url origin | sed -e 's/git@bitbucket.org:\(.*\).git/\1/')
# Get access token
access_token=$(curl -s -X "POST" "https://bitbucket.org/site/oauth2/access_token" \
-H 'Content-Type: application/x-www-form-urlencoded; charset=utf-8' \
--data-urlencode "client_id=$BITBUCKET_CLIENT_ID" \
--data-urlencode "client_secret=$BITBUCKET_CLIENT_SECRET" \
--data-urlencode "grant_type=client_credentials" | sed -n 's|.*"access_token": "\([^"]*\)".*|\1|p')
# Create PR
url=$(curl -s -X "POST" "https://api.bitbucket.org/2.0/repositories/$repo/pullrequests" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $access_token" \
-d "{\"title\":\"$title\",\"source\":{\"branch\":{\"name\":\"$branch\"}}}" | jq -r .links.html.href)
echo $url
# Copy PR URL to clipboard - works on Mac
echo $url | pbcopy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment