Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TFS REST API get latest successful build on a branch

Tags:

rest

tfs

I'm trying to get the latest build for a TFS definition. But I get all the sourceBranch values and I want to filter in the same query as I did on TeamCity. Is this possible in TFS or not?

The query I'm using is similar to:

url/builds?statusFilter=completed&resultFilter=succeeded&definitions=10&api-version=2.0

According the documentation provided https://www.visualstudio.com/en-us/docs/integrate/api/build/builds#get-a-build cannot find an easy way to query in the same request.

Does anyone did it before? I think it's pretty basic but difficult in TFS.

like image 801
Allan.C Avatar asked Mar 08 '23 03:03

Allan.C


1 Answers

By default, there isn't the Branch filter for the REST API to Get a list of builds.

GET https://{instance}/DefaultCollection/{project}/_apis/build/builds?api-version={version}[&definitions={string}][&queues={string}][&buildNumber={string}][&type={string}][&minFinishTime={DateTime}][&maxFinishTime={DateTime}][&requestedFor={string}][&reasonFilter={string}][&statusFilter={string}][&tagFilters={string}][&propertyFilters={string}][&$top={int}][&continuationToken={string}]

If you want to query the build on a specific branch use the REST API directly, you can use other filters, eg tagFilters, that means you can create tag for the builds which queued on the specific branch.

Another workaround is filter the branch with third tools, eg PowerShell.

You can use below PowerShell script to filter out the builds on specific branch (The first build should be the latest one):

$baseUrl = "http://server:8080/tfs/CollectionLC/0418Scrum/_apis/build/builds?api-version=2.0&statusFilter=completed&resultFilter=succeeded&definitions=57"  # Filter added.         
$builds = (Invoke-RestMethod -Uri $baseUrl -Method Get -UseDefaultCredential).value|where({$_.sourceBranch -eq '$/0418Scrum/web0418'}) # filter branch, just change '$/0418Scrum/web0418' to your branch.

$BuildResults = @()

foreach($build in $builds){

    $customObject = new-object PSObject -property @{
          "BuildDefinition" = $build.definition.name
          "BuildId" = $build.id
          "BuildNumber" = $build.buildNumber
          "status" = $build.status
          "result" = $build.result
          "finishTime" = $build.finishTime
          "sourceBranch" = $build.sourceBranch
        } 

    $BuildResults += $customObject      
}

$BuildResults | Select `
                BuildDefinition,
                BuildId, 
                BuildNumber, 
                status,
                result,
                finishTime,
                sourceBranch

enter image description here

like image 87
Andy Li-MSFT Avatar answered Mar 14 '23 20:03

Andy Li-MSFT