Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get real source branch name in VSTS Pull Request

We are using Visual Studio Team Systems with Git and Team System Build (former Build vNext). When we conduct a Pull Request, a new Build is triggered that is used to run Unit Tests and deploy to an isolated test system. To perform the deployment to an isolated system I need to get the real source branch name inside the build process. However the Build.SourceBranchName variable is always "merge",

E.g.:

Pull Request from source FOO to target BAR Build.SourceBranch is "refs/pull/1/merge" and therefore Build.SourceBranchName is "merge". But i need to somehow get "FOO" to run my Power Shell script to configure the system.

Is there a way to get the real source branch name inside a Git Pull Request inside VSTS?

like image 687
wertzui Avatar asked Jun 27 '16 06:06

wertzui


2 Answers

VSTS now has System.PullRequest.SourceBranch and System.PullRequest.TargetBranch variables. That should solve your problem without writing any custom scripts

Build Variables

like image 132
Ondra Avatar answered Oct 03 '22 17:10

Ondra


There isn't any variable for this but you can create a power-shell script to get it via Rest API.

[String]$projecturi = "$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"
[String]$sourcebranch = "$env:BUILD_SOURCEBRANCH"
[String]$repoid = "$env:BUILD_REPOSITORY_ID"

$username="alternativeusername"
$password="alternativepassword"

$basicAuth= ("{0}:{1}"-f $username,$password)
$basicAuth=[System.Text.Encoding]::UTF8.GetBytes($basicAuth)
$basicAuth=[System.Convert]::ToBase64String($basicAuth)
$headers= @{Authorization=("Basic {0}"-f $basicAuth)}

#get pull request ID via regex
$pullrequest = "refs/pull/+(?<pullnumber>\w+?)/merge+"
if($sourcebranch -match $pullrequest){        
        $pullrequestid = $Matches.pullnumber;
    }
else { write-host "Cannot find pull request ID" }

#get pull request information via API
$url= $projecturi + "_apis/git/repositories/" + $repoid + "/pullRequests/" + $pullrequestid + "?api-version=1.0-preview.1"

Write-Host $url

$getpullrequest = Invoke-RestMethod -Uri $url -headers $headers -Method Get

#get sourcebranch and targetbranch
$sourceref = $getpullrequest.sourceRefName
$targetref = $getpullrequest.targetRefName
like image 28
Eddie Chen - MSFT Avatar answered Oct 03 '22 18:10

Eddie Chen - MSFT