Create Pull Requests programmatically in BitBucket
On this one large project the bitbucket account has about 50 git repos in Atlassian BitBucket Cloud. Many of them are microservices that have e.g. similar Jenkinsfile, Dockerfile etc. Sometimes we need to make just one tweak across a whole bunch of repos, say to change the URL for a server because it was not parametrized. With JetBrains IDE (like IntelliJ, PyCharm, etc), it’s easy to do a search & replace, and then to do a bulk commit of all 50 repos for that one small change as you can use the same commit message, same referenced JIRA ticket number etc. A couple of button clicks and you’re done that part, piece of cake.
But then you have to create 50 pull requests!! I have no patience for that type of repetitive work. After a bit of digging and trial and error, I found a convenient way to create pull requests programmatically using bitbucket’s REST API:
- Create one PR in the web UI on one of the repos. Write a useful title, description, select all the reviewers you might need across all repos, and don’t forget to checkmar the “Delete branch on merge”.
- From a terminal shell, use
curl https://api.bitbucket.org/2.0/repositories/YOUR_ORG_NAME/REPO_NAME/pullrequests/PR_NUMBER_JUST_CREATED -u USERNAME:PASSWORD | jq . > pr_get.json
to get the JSON of that PR into a file. Note that your username is the one defined in your Profile Settings, and can be changed. For me it is not the name I use to login with. - Edit the file to remove most elements of it, keeping only the following:
description
,title
,close_source_branch
,reviewers
, andsource
- In
source
element, keep onlybranch
, remove the rest. - In the shell, use
for repo in $REPOS; do curl -s https://api.bitbucket.org/2.0/repositories/YOUR_ORG_NAME/$repo/pullrequests --user USERNAME:PASSWORD --request POST --header 'Content-Type: application/json' --data @pr_get.json; done
whereREPOS
is your list of repos. SoREPOS
could be*
if all folders in local folder are bitbucket git repos, or*-service
if all bitbucket repos of interest end in-service
, etc. You could get fancier and only do thecurl
ifgit status
shows changes, etc.
You’re done! Visit bitbucket and marvel that all your Pull Requests are created.
PS. If you also want to merge the PRs created this way, before doing the above look at my other post Merge Pull Requests programmatically in BitBucket, as there is one small change to make.