VSTS build script: Tagging build

Hey everyone,

I was recently working on my build & release flows for my project at work, trying to optimise it as much as possible.
I had the requirement that I only wanted 1 build definition, and 1 release definition per component.
The project consisted out of several components (e.g. an API, angularjs front-end, …) and I only wanted to release components which had changed.

I put together a powershell script which, when called as follows

.\TagBuild.ps1 -Tag Api -PathFilters sources/My.WebApi,sources/My.DAL,sources/My.Common

would tag my VSTS build with the tag Api when any files were changed in the paths sources/My.WebApi/*, sources/My.DAL/* or sources/My.Common/*

Then I could update my release definition for my API to only trigger an automated release if the build was tagged with Api

The script:


[CmdletBinding()]
param(
    [Parameter(mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Tag,

     [Parameter(mandatory=$true)]
    [string[]]$PathFilters = @(),

    [string]$UseVerbose = "false"
)
begin {
    $CurrentVerbosePreference = $VerbosePreference;

    if($VerbosePreference -eq "SilentlyContinue" -And $UseVerbose -eq "true") {
        $VerbosePreference = "continue"
    }
	
    
    if($PathFilters.Length -eq 0)
    {
        Write-Verbose 'No path filters provided, stopping prematurely'
        exit 0
    }

    Write-Host "Tag: $Tag"
    Write-Host "Filters: $PathFilters"
}
process {
    # Get changes
    $changes=$(git diff head head~ --name-only)

    foreach($file in $changes){
        
        if($null -ne ($PathFilters | ? { $file.StartsWith($_) })){
            Write-Verbose "$File matches a filter, tagging build."
            Write-Host "##vso[build.addbuildtag]$Tag"
            break
        }
        else{
            Write-Verbose "$File - NO MATCH"
        }
    }
}
end {
    $VerbosePreference = $CurrentVerbosePreference
}

Leave a Reply

Your email address will not be published.

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.