Search code examples
azure-devopsazure-repos

In Azure devops, how can I create a pull request from the command line that includes all work items from the source branch


In our project, we move from one stage of the application (beta/preprod/release) to another by creating a pull request between the source branch into the target one (e.g., "release/xxx" to "prod") using the Azure devops web interface.

After selecting the source and target branches, the devops web interface presents us with a list of all work items linked with the source branch and not the target branch. We use that list to prepare the release notes and to track the deployment of work items to the various code branches.

I would like to automate the creation of that pull request from the command-line using az report pr create to limit errors and save time.

I have been able to create the pull request almost exactly like I want but one element still eludes me: instead of having all the work items from the source branch (and not in the target branch) linked to my PR, the linked work items list is empty.

Is there a way to do that using the command-line?


Solution

  • Work items are associated to commits.

    The following example shows how to get all the DISTINCT work item IDs linked to the commits of a specific branch:

    ORGANIZATION="https://dev.azure.com/MY-ORGANIZATION"
    PROJECT="MY-PROJECT"
    REPO="MY-REPOSITORY"
    BRANCH="MY-BRANCH"
    
    # az devops login
    
    work_item_ids=$(\
      az devops invoke --area git --resource commits \
      --route-parameters project=$PROJECT repositoryId=$REPO \
      --query-parameters \
          searchCriteria.itemVersion.version=$BRANCH \
          searchCriteria.includeWorkItems=true \
      --api-version 7.1 --org $ORGANIZATION \
      | jq -r '.value[] | .workItems[]?.id' | sort | uniq \
    )
    
    printf "Work items linked to branch $BRANCH:\n%s\n" "$work_item_ids"
    
    # Convert to a comma-separated list of work item ids
    work_item_ids=$(echo "$work_item_ids" | paste -sd, -)
    
    printf "Work items linked to branch $BRANCH: \n%s\n" "$work_item_ids"
    

    Example output:

    Work items linked to branch main: 
    170
    174
    Work items linked to branch main: 
    170,174
    

    Please note that az devops invoke command is a wrapper (sort of) for the Azure DevOps REST API. In this case, we're invoking the Get Commits endpoint:

    GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/commits?api-version=7.1