skip to Main Content

In Azure Dev Ops, given a branch name, how I do I get the corresponding Pull Request (if one exists).

I have a local branch named FooBranch which I’ve pushed to the remote repo BarRepo which lives in Azure DevOps. I created a Pull Request in the BarRepo repo from the branch FooBranch.

The is the branch’s Url
https://{org}.visualstudio.com/{project}/_git/BarRepo?version=GBFooBranch

The PR url looks like this
https://{org}.visualstudio.com/{project}/_git/BarRepo/pullrequest/{prID}
where {prID} is an 8-digit number.

Given the branch BarRepo how do I determine {prID}? I would like to do this in a PowerShell script if possible. Maybe thru the Azure CLI. Or via an HTTP req.


I know not all branches will have an associated PR. Can a branch be in several PRs?

2

Answers


  1. You can use the az repos pr list command to list pull requests and filter results by both source and target branch (among others), if needed:

    az repos pr list [--creator]
                     [--detect {false, true}]
                     [--include-links]
                     [--org]
                     [--project]
                     [--repository]
                     [--reviewer]
                     [--skip]
                     [--source-branch]
                     [--status {abandoned, active, all, completed}]
                     [--target-branch]
                     [--top]
    

    Sample YAML pipeline:

    trigger: none
    
    steps:
      - checkout: none
      - script: |
          az repos pr list 
            --organization $(System.CollectionUri) 
            --project $(System.TeamProject) 
            --repository dummy 
            --status active 
            --source-branch foo 
            --output json
        displayName: 'List PRs'
        env:
          AZURE_DEVOPS_EXT_PAT: $(System.AccessToken)
    

    Sample response:

    [
      {
        "artifactId": null,
        "autoCompleteSetBy": null,
        "closedBy": null,
        "closedDate": null,
        "codeReviewId": 56,
        "commits": null,
        "completionOptions": null,
        "completionQueueTime": null,
        "createdBy": {
          "descriptor": "aad.xxxxxxxxxxxxx",
          "directoryAlias": null,
          "displayName": "Bruce Wayne",
          "id": "aaaaaaaaaaaaaaaaaaa",
          "imageUrl": "https://dev.azure.com/brucewayne/_api/_common/identityImage?id=aaaaaaaaaaaaaaaaaaa",
          "inactive": null,
          "isAadIdentity": null,
          "isContainer": null,
          "isDeletedInOrigin": null,
          "profileUrl": null,
          "uniqueName": "[email protected]",
          "url": "https://spsprodeus21.vssps.visualstudio.com/bbbbbbbbbbbbbbbbbb/_apis/Identities/aaaaaaaaaaaaaaaaaaa"
        },
        "creationDate": "2024-07-17T14:22:20.079357+00:00",
        "description": "Dummy PR",
        "forkSource": null,
        "isDraft": false,
        "labels": null,
        "lastMergeCommit": {
          "author": null,
          "changeCounts": null,
          "changes": null,
          "comment": null,
          "commentTruncated": null,
          "commitId": "ccccccccccccccccccccccc",
          "committer": null,
          "parents": null,
          "push": null,
          "remoteUrl": null,
          "statuses": null,
          "url": "https://dev.azure.com/brucewayne/ddddddddddddddddd/_apis/git/repositories/eeeeeeeeeeeeeeeee/commits/ccccccccccccccccccccccc",
          "workItems": null
        },
        "lastMergeSourceCommit": {
          "author": null,
          "changeCounts": null,
          "changes": null,
          "comment": null,
          "commentTruncated": null,
          "commitId": "ffffffffffffffffff",
          "committer": null,
          "parents": null,
          "push": null,
          "remoteUrl": null,
          "statuses": null,
          "url": "https://dev.azure.com/brucewayne/ddddddddddddddddd/_apis/git/repositories/eeeeeeeeeeeeeeeee/commits/ffffffffffffffffff",
          "workItems": null
        },
        "lastMergeTargetCommit": {
          "author": null,
          "changeCounts": null,
          "changes": null,
          "comment": null,
          "commentTruncated": null,
          "commitId": "ggggggggggggg",
          "committer": null,
          "parents": null,
          "push": null,
          "remoteUrl": null,
          "statuses": null,
          "url": "https://dev.azure.com/brucewayne/ddddddddddddddddd/_apis/git/repositories/eeeeeeeeeeeeeeeee/commits/ggggggggggggg",
          "workItems": null
        },
        "mergeFailureMessage": null,
        "mergeFailureType": null,
        "mergeId": "hhhhhhhhhhhhhhhh",
        "mergeOptions": null,
        "mergeStatus": "succeeded",
        "pullRequestId": 56,
        "remoteUrl": null,
        "repository": {
          "defaultBranch": null,
          "id": "eeeeeeeeeeeeeeeee",
          "isFork": null,
          "name": "dummy",
          "parentRepository": null,
          "project": {
            "abbreviation": null,
            "defaultTeamImageUrl": null,
            "description": null,
            "id": "ddddddddddddddddd",
            "lastUpdateTime": "0001-01-01T00:00:00",
            "name": "brucewayne",
            "revision": null,
            "state": "unchanged",
            "url": null,
            "visibility": "unchanged"
          },
          "remoteUrl": null,
          "size": null,
          "sshUrl": null,
          "url": "https://dev.azure.com/brucewayne/ddddddddddddddddd/_apis/git/repositories/eeeeeeeeeeeeeeeee",
          "validRemoteUrls": null
        },
        "reviewers": [],
        "sourceRefName": "refs/heads/foo",
        "status": "active",
        "supportsIterations": true,
        "targetRefName": "refs/heads/main",
        "title": "Dummy PR",
        "url": "https://dev.azure.com/brucewayne/ddddddddddddddddd/_apis/git/repositories/eeeeeeeeeeeeeeeee/pullRequests/56",
        "workItemRefs": null
      }
    ]
    

    Given the branch BarRepo how do I determine {prID}?

    Correspondent property in the above response is pullRequestId.

    Login or Signup to reply.
  2. I know not all branches will have an associated PR. Can a branch be in several PRs?

    Yes, a branch can be linked to multiple PRs if it’s used as the source for different target branches or if multiple PRs are created from it. For example, a feature branch might have PRs for both the development and release branches, each with a different PR ID but sharing the same source branch.

    Given the branch BarRepo how do I determine {prID}? I would like to do this in a PowerShell script if possible. Maybe the Azure CLI. Or via an HTTP req.

    1. Using Azure CLI az repos pr list sample PowerShell task:
    steps:
      - powershell:  |
          $organization = ""
          $project = ""
          $repositoryName= ""
          $sourcebranch = ""     
    
          $prs = az repos pr list --organization https://dev.azure.com/$organization --project $project --repository $repositoryName --source-branch $sourcebranch --output json
    
          # Parse the JSON response
          $prsJson = $prs | ConvertFrom-Json
    
          # Check if any PRs are found
          if ($prsJson.Count -eq 0) {
              Write-Output "No Pull Requests found for branch: $sourcebranch"
          } else {
              # Get all PR IDs
              $prIds = $prsJson.pullRequestId
              Write-Output "Pull Request IDs: $prIds"
          }
        displayName: 'az repos pr list'
        env:
          AZURE_DEVOPS_EXT_PAT: $(System.AccessToken)
    
    

    Test result:

    result1

    1. Using REST API Pull Requests – Get Pull Requests sample PowerShell task:
    steps:
      - task: PowerShell@2
        displayName: 'REST API'
        inputs:
          targetType: 'inline'
          script: |
            # Set variables
            $organization = ""
            $project = ""
            $repositoryName= ""
            $sourcebranch = ""
            
            # Create the API URL
            $apiUrl = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repositoryName/pullrequests?searchCriteria.sourceRefName=refs/heads/$sourcebranch&api-version=7.1-preview.1"
            
            # Make the HTTP GET request
            $response = Invoke-RestMethod -Uri $apiUrl -Method Get -Headers @{Authorization = "Bearer $(System.AccessToken)"} 
            
            # Check if any PRs are found
            if ($response.value.Count -eq 0) {
                Write-Output "No Pull Requests found for branch: $sourcebranch"
            } else {
                # Get all PR IDs
                $prIds = $response.value.pullRequestId
                Write-Output "Pull Request IDs: $prIds"
            }
    

    Test result:

    result

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search