Created
October 31, 2018 13:21
-
-
Save vtml/946e8d65689ed6c2a9847de133f6431c to your computer and use it in GitHub Desktop.
TeamCity Build Step to determine last successful build Git Commit ID
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
###################################################### | |
# Retrieves the last successful build of a TeamCity Project | |
# Finding the Commit Hash | |
# http://blogs.lessthandot.com/index.php/uncategorized/access-git-commits-during-a-teamcity-build-using-powershell/ | |
###################################################### | |
function Get-TeamCityLastSuccessfulRun([string] $TeamCityUrl, [string] $TeamCityBuildTypeId, [string] $TeamCityUsername, [string] $TeamCityPassword) | |
{ | |
$Credentials = "$($TeamCityUsername):$($TeamCityPassword)" | |
$AuthString = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$Credentials")) | |
$Url = "$($TeamCityUrl)/app/rest/buildTypes/id:$($TeamCityBuildTypeId)/builds/status:SUCCESS,count:1" | |
$Content = Invoke-WebRequest "$Url" -Headers @{"Authorization" = "Basic $AuthString"} | |
return $Content | |
} | |
function Get-LatestSuccessfulRunCommitHash([string] $TeamCityUrl, [string] $TeamCityBuildTypeId, [string] $TeamCityUsername, [string] $TeamCityPassword) | |
{ | |
$Run = Get-TeamCityLastSuccessfulRun -TeamCityUrl "$TeamCityUrl" -TeamCityBuildTypeId "$TeamCityBuildTypeId" -TeamCityUsername "$TeamCityUsername" -TeamCityPassword "$TeamCityPassword" | |
Write-Host "$Run" | |
$LatestCommitFromRun = (Select-Xml -Content "$Run" -Xpath "/build/revisions/revision/@version").Node.Value | |
return $LatestCommitFromRun | |
} | |
$LastGitCommitId = "%env.LastSuccessfulRunGitCommitId%" | |
# Only try to process if the Last Git Commit Id is not passed in as a run-time parameter | |
if (!$LastGitCommitId) | |
{ | |
$LastGitCommitId = Get-LatestSuccessfulRunCommitHash -TeamCityUrl "%teamcity.serverUrl%" -TeamCityBuildTypeId "%system.teamcity.buildType.id%" -TeamCityUsername "%system.teamcity.auth.userId%" -TeamCityPassword "%system.teamcity.auth.password%" | |
# Set the TeamCity variable | |
Write-Host "##teamcity[setParameter name='env.LastSuccessfulRunGitCommitId' value='$LastGitCommitId']" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment