Skip to content

Instantly share code, notes, and snippets.

@Tiberriver256
Created August 28, 2024 23:29
Show Gist options
  • Save Tiberriver256/99452a6bd254327acceb0405e34d2230 to your computer and use it in GitHub Desktop.
Save Tiberriver256/99452a6bd254327acceb0405e34d2230 to your computer and use it in GitHub Desktop.
A PowerShell script to get associated work items for an Azure DevOps build
#Requires -PSEdition Core
<#
.SYNOPSIS
Retrieves distinct commits and associated work items for a build pipeline... with support for monorepos!
See the blog post at https://tiberriver256.github.io/DevOps/azure-devops-pipelines-related-work-items-monorepo for more information.
.DESCRIPTION
This script retrieves the distinct commits and associated work items for a build pipeline. It requires the following parameters:
- BuildId: The ID of the build. If not provided, it uses the value of the environment variable BUILD_BUILDID.
- CollectionUri: The URI of the collection. If not provided, it uses the value of the environment variable SYSTEM_COLLECTIONURI.
- ProjectId: The ID of the project. If not provided, it uses the value of the environment variable SYSTEM_TEAMPROJECTID.
- AuthorizationHeader: The authorization header. If not provided, it uses the value of the environment variable SYSTEM_ACCESSTOKEN.
.PARAMETER BuildId
The ID of the build.
.PARAMETER CollectionUri
The URI of the collection.
.PARAMETER ProjectId
The ID of the project.
.PARAMETER AuthorizationHeader
The authorization header.
.OUTPUTS
Returns a PSCustomObject with the following properties:
- DistinctCommits: An array of distinct commits.
- AssociatedWorkItems: An array of associated work items.
.EXAMPLE
Get-BuildPipelineScopedChanges -BuildId 12345 -CollectionUri "https://dev.azure.com/myorg/" -ProjectId "be77c668-1e13-4360-aa08-264b1d5f64c6" -AuthorizationHeader "Bearer <access_token>"
Retrieves the distinct commits and associated work items for the build with ID 12345 in the project "be77c668-1e13-4360-aa08-264b1d5f64c6" in the Azure DevOps organization "myorg" using the specified access token.
#>
[CmdletBinding()]
param (
[Parameter()]
[int]
$BuildId = $ENV:BUILD_BUILDID,
[Parameter()]
[Uri]
$CollectionUri = $ENV:SYSTEM_COLLECTIONURI,
[Parameter()]
[Guid]
$ProjectId = $ENV:SYSTEM_TEAMPROJECTID,
[Parameter()]
$AuthorizationHeader = "Bearer $ENV:SYSTEM_ACCESSTOKEN"
)
function EnsureModuleInstalled ( $name ) {
$module = Get-InstalledModule -Name $name
if ($null -eq $module) {
Install-Module -Name $name -Scope CurrentUser -AllowClobber
}
}
EnsureModuleInstalled "powershell-yaml"
$Headers = @{
Authorization = $AuthorizationHeader
}
$BuildUri = "$CollectionUri$ProjectId/_apis/build/builds/$BuildId"
$ChangesUri = "$CollectionUri$ProjectId/_apis/build/builds/$BuildId/changes"
$Build = Invoke-RestMethod -Uri $BuildUri -Headers $Headers
$RepositoryId = $Build.repository.id
$CommitId = $Build.sourceVersion
$BuildDefinitionId = $Build.definition.id
$BuildDefinitionRevision = $Build.definition.revision
$BuildDefinitionUri = "$CollectionUri$ProjectId/_apis/build/definitions/$($BuildDefinitionId)?revision=$BuildDefinitionRevision"
$BuildDefinition = Invoke-RestMethod -Uri $BuildDefinitionUri -Headers $Headers
$YamlFilePath = $BuildDefinition.process.yamlFilename
$YamlFileUri = "$CollectionUri$ProjectId/_apis/git/repositories/$RepositoryId/items?path=$YamlFilePath&download=true&versionDescriptor.version=$CommitId&versionDescriptor.versionType=commit"
$YamlFile = Invoke-RestMethod -Uri $YamlFileUri -Headers $Headers | ConvertFrom-Yaml
$TriggerPaths = $YamlFile.trigger.paths.include | ForEach-Object { $_ -replace "\*", "" }
$IsMonoRepo = $TriggerPaths.Count -ge 1 -and $TriggerPaths[0] -ne "/"
$Changes = Invoke-RestMethod -Uri $ChangesUri -Headers $Headers
$LatestChangeTimeStamp = $Changes.value[0].timestamp
$OldestChangeTimeStamp = $Changes.value[-1].timestamp
$CommitsFilteredByTriggerPaths = @()
$BaseCommitsUri = "$CollectionUri$ProjectId/_apis/git/repositories/$RepositoryId/commits?searchCriteria.fromDate=$OldestChangeTimeStamp&searchCriteria.toDate=$LatestChangeTimeStamp&searchCriteria.includeWorkItems=true"
if ($IsMonoRepo) {
foreach ($Path in $TriggerPaths) {
$CommitsUri = "$BaseCommitsUri&searchCriteria.itemPath=$Path"
$Commits = Invoke-RestMethod -Uri $CommitsUri -Headers $Headers
$CommitsFilteredByTriggerPaths += $Commits.value
}
}
else {
$Commits = Invoke-RestMethod -Uri $BaseCommitsUri -Headers $Headers
$CommitsFilteredByTriggerPaths = $Commits.value
}
$DistinctCommits = @($CommitsFilteredByTriggerPaths |
Group-Object -Property commitId |
ForEach-Object { $_.Group[0] })
$DistinctWorkItemUrls = $DistinctCommits.workItems.url | Get-Unique
$AssociatedWorkItems = @($DistinctWorkItemUrls | ForEach-Object {
Invoke-RestMethod -Uri $_ -Headers $Headers
})
return [PSCustomObject]@{
DistinctCommits = $DistinctCommits
AssociatedWorkItems = $AssociatedWorkItems
}

The MIT License (MIT)

Copyright (c) 2016 Tiberriver256

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment