DEV Community

schollii
schollii

Posted on

Create and Merge Pull Requests Programmatically in BitBucket

On this one large project the bitbucket account has a large number of git repos in Atlassian BitBucket Cloud. Sometimes for one JIRA ticket, we need to fix code across a whole bunch of repos, say to change the URL for a server because it was not parametrized, or to adopt a new naming convention. With JetBrains IDE (like IntelliJ, PyCharm, etc), it’s easy to do a bulk commit of all repos for that one 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. Or just use a for loop in bash if you prefer to work in terminal.

But then you have to create a pull request for each repo, ouch!! Each one will likely have the same set of reviewers, same description, etc. I have no patience for that type of repetitive work. And pycharm (as of 2020.1) provides no assistance here.

After a bit of digging and trial and error, I found a convenient way to create pull requests programmatically using bitbucket’s REST API, and after they have all be reviewed and approved, to merge them.

  1. 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. Don’t forget to checkmark the "Delete branch on merge" if that is part of your process.
  2. After the PR is created, note its number in the URL (let's call it PR_NUMBER_JUST_CREATED).
  3. From a terminal shell, use this 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.

    BB_URL=https://api.bitbucket.org/2.0/repositories/YOUR_ORG_NAME
    PR_NUMBER_JUST_CREATED=<PR_NUMBER_JUST_CREATED>
    curl $BB_URL/REPO_NAME/pullrequests/$PR_NUMBER_JUST_CREATED \
        -u USERNAME:PASSWORD | jq . > pr_get.json
    
  4. Edit the file to remove most elements of it, keeping only the following: description, title, close_source_branch, reviewers, and source

  5. In source element, keep only branch, remove the rest.

  6. Create the remaining PR's programmatically:

    for repo in $REPOS; do 
        curl -s $BB_URL/$repo/pullrequests --user USERNAME:PASSWORD \
            --request POST --header 'Content-Type: application/json' \
            --data @pr_get.json \
        | jq -r .links.merge.href
    done > pr_merges.txt
    
  7. Once they are all ready for merging, run this:

    for merge in $( cat pr_merges.txt ); do
        curl $merge --user USERNAME:PASSWORD --request POST
    done
    

There's various improvements that could be done of course, say to turn these into a bash command, get password from stdin, etc. This has been good enough so far.

I posted this originally in Create Pull Requests programmatically in BitBucket and Merge Pull Requests programmatically in BitBucket.

Top comments (0)