1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
|
Set-StrictMode -Version "4.0"
class MatrixConfig {
[PSCustomObject]$displayNames
[Hashtable]$displayNamesLookup
[PSCustomObject]$matrix
[MatrixParameter[]]$matrixParameters
[Array]$include
[Array]$exclude
}
class MatrixParameter {
MatrixParameter([String]$name, [System.Object]$value) {
$this.Value = $value
$this.Name = $name
}
[System.Object]$Value
[System.Object]$Name
Set($value, [String]$keyRegex = '')
{
if ($this.Value -is [PSCustomObject]) {
$set = $false
foreach ($prop in $this.Value.PSObject.Properties) {
if ($prop.Name -match $keyRegex) {
$prop.Value = $value
$set = $true
break
}
}
if (!$set) {
throw "Property `"$keyRegex`" does not exist for MatrixParameter."
}
} else {
$this.Value = $value
}
}
[System.Object]Flatten()
{
if ($this.Value -is [PSCustomObject]) {
return $this.Value.PSObject.Properties | ForEach-Object {
[MatrixParameter]::new($_.Name, $_.Value)
}
} elseif ($this.Value -is [Array]) {
return $this.Value | ForEach-Object {
[MatrixParameter]::new($this.Name, $_)
}
} else {
return $this
}
}
[Int]Length()
{
if ($this.Value -is [PSCustomObject]) {
return ($this.Value.PSObject.Properties | Measure-Object).Count
} elseif ($this.Value -is [Array]) {
return $this.Value.Length
} else {
return 1
}
}
[String]CreateDisplayName([Hashtable]$displayNamesLookup)
{
if ($null -eq $this.Value) {
$displayName = ""
} elseif ($this.Value -is [PSCustomObject]) {
$displayName = $this.Name
} else {
$displayName = $this.Value.ToString()
}
if ($displayNamesLookup.ContainsKey($displayName)) {
$displayName = $displayNamesLookup[$displayName]
}
# Matrix naming restrictions:
# https://docs.microsoft.com/en-us/azure/devops/pipelines/process/phases?view=azure-devops&tabs=yaml#multi-job-configuration
$displayName = $displayName -replace "[^A-Za-z0-9_]", ""
return $displayName
}
}
$IMPORT_KEYWORD = '$IMPORT'
function GenerateMatrix(
[MatrixConfig]$config,
[String]$selectFromMatrixType,
[String]$displayNameFilter = ".*",
[Array]$filters = @(),
[Array]$replace = @(),
[Array]$nonSparseParameters = @()
) {
$matrixParameters, $importedMatrix, $combinedDisplayNameLookup = `
ProcessImport $config.matrixParameters $selectFromMatrixType $nonSparseParameters $config.displayNamesLookup
if ($selectFromMatrixType -eq "sparse") {
$matrix = GenerateSparseMatrix $matrixParameters $config.displayNamesLookup $nonSparseParameters
} elseif ($selectFromMatrixType -eq "all") {
$matrix = GenerateFullMatrix $matrixParameters $config.displayNamesLookup
} else {
throw "Matrix generator not implemented for selectFromMatrixType: $($platform.selectFromMatrixType)"
}
# Combine with imported after matrix generation, since a sparse selection should result in a full combination of the
# top level and imported sparse matrices (as opposed to a sparse selection of both matrices).
if ($importedMatrix) {
$matrix = CombineMatrices $matrix $importedMatrix $combinedDisplayNameLookup
}
if ($config.exclude) {
$matrix = ProcessExcludes $matrix $config.exclude
}
if ($config.include) {
$matrix = ProcessIncludes $config $matrix $selectFromMatrixType
}
$matrix = FilterMatrix $matrix $filters
$matrix = ProcessReplace $matrix $replace $config.displayNamesLookup
$matrix = FilterMatrixDisplayName $matrix $displayNameFilter
return $matrix
}
function ProcessNonSparseParameters(
[MatrixParameter[]]$parameters,
[Array]$nonSparseParameters
) {
if (!$nonSparseParameters) {
return $parameters, $null
}
$sparse = [MatrixParameter[]]@()
$nonSparse = [MatrixParameter[]]@()
foreach ($param in $parameters) {
if ($param.Name -in $nonSparseParameters) {
$nonSparse += $param
} else {
$sparse += $param
}
}
return $sparse, $nonSparse
}
function FilterMatrixDisplayName([array]$matrix, [string]$filter) {
return $matrix | Where-Object { $_ } | ForEach-Object {
if ($_.Name -match $filter) {
return $_
}
}
}
# Filters take the format of key=valueregex,key2=valueregex2
function FilterMatrix([array]$matrix, [array]$filters) {
$matrix = $matrix | ForEach-Object {
if (MatchesFilters $_ $filters) {
return $_
}
}
return $matrix
}
function MatchesFilters([hashtable]$entry, [array]$filters) {
foreach ($filter in $filters) {
$key, $regex = ParseFilter $filter
# Default all regex checks to go against empty string when keys are missing.
# This simplifies the filter syntax/interface to be regex only.
$value = ""
if ($null -ne $entry -and $entry.parameters.Contains($key)) {
$value = $entry.parameters[$key]
}
if ($value -notmatch $regex) {
return $false
}
}
return $true
}
function ParseFilter([string]$filter) {
# Lazy match key in case value contains '='
if ($filter -match "(.+?)=(.+)") {
$key = $matches[1]
$regex = $matches[2]
return $key, $regex
} else {
throw "Invalid filter: `"${filter}`", expected <key>=<regex> format"
}
}
# Importing the JSON as PSCustomObject preserves key ordering,
# whereas ConvertFrom-Json -AsHashtable does not
function GetMatrixConfigFromJson([String]$jsonConfig)
{
[MatrixConfig]$config = $jsonConfig | ConvertFrom-Json
$config.matrixParameters = @()
$config.displayNamesLookup = @{}
$include = [MatrixParameter[]]@()
$exclude = [MatrixParameter[]]@()
if ($null -ne $config.displayNames) {
$config.displayNames.PSObject.Properties | ForEach-Object {
$config.displayNamesLookup.Add($_.Name, $_.Value)
}
}
if ($null -ne $config.matrix) {
$config.matrixParameters = PsObjectToMatrixParameterArray $config.matrix
}
foreach ($includeMatrix in $config.include) {
$include += ,@(PsObjectToMatrixParameterArray $includeMatrix)
}
foreach ($excludeMatrix in $config.exclude) {
$exclude += ,@(PsObjectToMatrixParameterArray $excludeMatrix)
}
$config.include = $include
$config.exclude = $exclude
return $config
}
function PsObjectToMatrixParameterArray([PSCustomObject]$obj)
{
if ($obj -eq $null) {
return $null
}
return $obj.PSObject.Properties | ForEach-Object {
[MatrixParameter]::new($_.Name, $_.Value)
}
}
function ProcessExcludes([Array]$matrix, [Array]$excludes)
{
$deleteKey = "%DELETE%"
$exclusionMatrix = @()
foreach ($exclusion in $excludes) {
$full = GenerateFullMatrix $exclusion
$exclusionMatrix += $full
}
foreach ($element in $matrix) {
foreach ($exclusion in $exclusionMatrix) {
$match = MatrixElementMatch $element.parameters $exclusion.parameters
if ($match) {
$element.parameters[$deleteKey] = $true
}
}
}
return $matrix | Where-Object { !$_.parameters.Contains($deleteKey) }
}
function ProcessIncludes([MatrixConfig]$config, [Array]$matrix)
{
$inclusionMatrix = @()
foreach ($inclusion in $config.include) {
$full = GenerateFullMatrix $inclusion $config.displayNamesLookup
$inclusionMatrix += $full
}
return $matrix + $inclusionMatrix
}
function ParseReplacement([String]$replacement) {
$parsed = '', '', ''
$idx = 0
$escaped = $false
$operators = '=', '/'
$err = "Invalid replacement syntax, expecting <key>=<value>/<replace>"
foreach ($c in $replacement -split '') {
if ($idx -ge $parsed.Length) {
throw $err
}
if (!$escaped -and $c -in $operators) {
$idx++
} else {
$parsed[$idx] += $c
}
$escaped = $c -eq '\'
}
if ($idx -lt $parsed.Length - 1) {
throw $err
}
$replace = $parsed[2] -replace "\\([$($operators -join '')])", '$1'
return @{
"key" = '^' + $parsed[0] + '$'
# Force full matches only.
"value" = '^' + $parsed[1] + '$'
"replace" = $replace
}
}
function ProcessReplace
{
param(
[Array]$matrix,
[Array]$replacements,
[Hashtable]$displayNamesLookup
)
if (!$replacements) {
return $matrix
}
$replaceMatrix = @()
foreach ($element in $matrix) {
$replacement = [MatrixParameter[]]@()
foreach ($perm in $element._permutation) {
$replace = $perm
# Iterate nested permutations or run once for singular values (int, string, bool)
foreach ($flattened in $perm.Flatten()) {
foreach ($query in $replacements) {
$parsed = ParseReplacement $query
if ($flattened.Name -match $parsed.key -and $flattened.Value -match $parsed.value) {
# In most cases, this will just swap one value for another, however -replace
# is used here in order to support replace values which may use regex capture groups
# e.g. 'foo-1' -replace '(foo)-1', '$1-replaced'
$replaceValue = $flattened.Value -replace $parsed.value, $parsed.replace
$perm.Set($replaceValue, $parsed.key)
break
}
}
}
$replacement += $perm
}
$replaceMatrix += CreateMatrixCombinationScalar $replacement $displayNamesLookup
}
return $replaceMatrix
}
function ProcessImport([MatrixParameter[]]$matrix, [String]$selection, [Array]$nonSparseParameters, [Hashtable]$displayNamesLookup)
{
$importPath = ""
$matrix = $matrix | ForEach-Object {
if ($_.Name -ne $IMPORT_KEYWORD) {
return $_
} else {
$importPath = $_.Value
}
}
if ((!$matrix -and !$importPath) -or !$importPath) {
return $matrix, @()
}
if (!(Test-Path $importPath)) {
Write-Error "`$IMPORT path '$importPath' does not exist."
exit 1
}
$importedMatrixConfig = GetMatrixConfigFromJson (Get-Content $importPath)
$importedMatrix = GenerateMatrix `
-config $importedMatrixConfig `
-selectFromMatrixType $selection `
-nonSparseParameters $nonSparseParameters
$combinedDisplayNameLookup = $importedMatrixConfig.displayNamesLookup
foreach ($lookup in $displayNamesLookup.GetEnumerator()) {
$combinedDisplayNameLookup[$lookup.Name] = $lookup.Value
}
return $matrix, $importedMatrix, $importedMatrixConfig.displayNamesLookup
}
function CombineMatrices([Array]$matrix1, [Array]$matrix2, [Hashtable]$displayNamesLookup = @{})
{
$combined = @()
if (!$matrix1) {
return $matrix2
}
if (!$matrix2) {
return $matrix1
}
foreach ($entry1 in $matrix1) {
foreach ($entry2 in $matrix2) {
$combined += CreateMatrixCombinationScalar ($entry1._permutation + $entry2._permutation) $displayNamesLookup
}
}
return $combined
}
function MatrixElementMatch([System.Collections.Specialized.OrderedDictionary]$source, [System.Collections.Specialized.OrderedDictionary]$target)
{
if ($target.Count -eq 0) {
return $false
}
foreach ($key in $target.Keys) {
if (!$source.Contains($key) -or $source[$key] -ne $target[$key]) {
return $false
}
}
return $true
}
function CloneOrderedDictionary([System.Collections.Specialized.OrderedDictionary]$dictionary) {
$newDictionary = [Ordered]@{}
foreach ($element in $dictionary.GetEnumerator()) {
$newDictionary[$element.Name] = $element.Value
}
return $newDictionary
}
function SerializePipelineMatrix([Array]$matrix)
{
$pipelineMatrix = [Ordered]@{}
foreach ($entry in $matrix) {
if ($pipelineMatrix.Contains($entry.Name)) {
Write-Warning "Found duplicate configurations for job `"$($entry.name)`". Multiple values may have been replaced with the same value."
continue
}
$pipelineMatrix.Add($entry.name, [Ordered]@{})
foreach ($key in $entry.parameters.Keys) {
$pipelineMatrix[$entry.name].Add($key, $entry.parameters[$key])
}
}
return @{
compressed = $pipelineMatrix | ConvertTo-Json -Compress ;
pretty = $pipelineMatrix | ConvertTo-Json;
}
}
function GenerateSparseMatrix(
[MatrixParameter[]]$parameters,
[Hashtable]$displayNamesLookup,
[Array]$nonSparseParameters = @()
) {
$parameters, $nonSparse = ProcessNonSparseParameters $parameters $nonSparseParameters
$dimensions = GetMatrixDimensions $parameters
$matrix = GenerateFullMatrix $parameters $displayNamesLookup
$sparseMatrix = @()
[array]$indexes = GetSparseMatrixIndexes $dimensions
foreach ($idx in $indexes) {
$sparseMatrix += GetNdMatrixElement $idx $matrix $dimensions
}
if ($nonSparse) {
$allOfMatrix = GenerateFullMatrix $nonSparse $displayNamesLookup
return CombineMatrices $allOfMatrix $sparseMatrix $displayNamesLookup
}
return $sparseMatrix
}
function GetSparseMatrixIndexes([Array]$dimensions)
{
$size = ($dimensions | Measure-Object -Maximum).Maximum
$indexes = @()
# With full matrix, retrieve items by doing diagonal lookups across the matrix N times.
# For example, given a matrix with dimensions 3, 2, 2:
# 0, 0, 0
# 1, 1, 1
# 2, 2, 2
# 3, 0, 0 <- 3, 3, 3 wraps to 3, 0, 0 given the dimensions
for ($i = 0; $i -lt $size; $i++) {
$idx = @()
for ($j = 0; $j -lt $dimensions.Length; $j++) {
$idx += $i % $dimensions[$j]
}
$indexes += ,$idx
}
return ,$indexes
}
function GenerateFullMatrix(
[MatrixParameter[]] $parameters,
[Hashtable]$displayNamesLookup = @{}
) {
# Handle when the config does not have a matrix specified (e.g. only the include field is specified)
if (!$parameters) {
return @()
}
$matrix = [System.Collections.ArrayList]::new()
InitializeMatrix $parameters $displayNamesLookup $matrix
return $matrix
}
function CreateMatrixCombinationScalar([MatrixParameter[]]$permutation, [Hashtable]$displayNamesLookup = @{})
{
$names = @()
$flattenedParameters = [Ordered]@{}
foreach ($entry in $permutation) {
$nameSegment = ""
# Unwind nested permutations or run once for singular values (int, string, bool)
foreach ($param in $entry.Flatten()) {
if ($flattenedParameters.Contains($param.Name)) {
throw "Found duplicate parameter `"$($param.Name)`" when creating matrix combination."
}
$flattenedParameters.Add($param.Name, $param.Value)
}
$nameSegment = $entry.CreateDisplayName($displayNamesLookup)
if ($nameSegment) {
$names += $nameSegment
}
}
# The maximum allowed matrix name length is 100 characters
$name = $names -join "_"
if ($name -and $name[0] -match "^[0-9]") {
$name = "job_" + $name # Azure Pipelines only supports job names starting with letters
}
if ($name.Length -gt 100) {
$name = $name[0..99] -join ""
}
return @{
name = $name
parameters = $flattenedParameters
# Keep the original permutation around in case we need to re-process this entry when transforming the matrix
_permutation = $permutation
}
}
function InitializeMatrix
{
param(
[MatrixParameter[]]$parameters,
[Hashtable]$displayNamesLookup,
[System.Collections.ArrayList]$permutations,
$permutation = [MatrixParameter[]]@()
)
$head, $tail = $parameters
if (!$head) {
$entry = CreateMatrixCombinationScalar $permutation $displayNamesLookup
$permutations.Add($entry) | Out-Null
return
}
# This behavior implicitly treats non-array values as single elements
foreach ($param in $head.Flatten()) {
$newPermutation = $permutation + $param
InitializeMatrix $tail $displayNamesLookup $permutations $newPermutation
}
}
function GetMatrixDimensions([MatrixParameter[]]$parameters)
{
$dimensions = @()
foreach ($param in $parameters) {
$dimensions += $param.Length()
}
return $dimensions
}
function SetNdMatrixElement
{
param(
$element,
[ValidateNotNullOrEmpty()]
[Array]$idx,
[ValidateNotNullOrEmpty()]
[Array]$matrix,
[ValidateNotNullOrEmpty()]
[Array]$dimensions
)
if ($idx.Length -ne $dimensions.Length) {
throw "Matrix index query $($idx.Length) must be the same length as its dimensions $($dimensions.Length)"
}
$arrayIndex = GetNdMatrixArrayIndex $idx $dimensions
$matrix[$arrayIndex] = $element
}
function GetNdMatrixArrayIndex
{
param(
[ValidateNotNullOrEmpty()]
[Array]$idx,
[ValidateNotNullOrEmpty()]
[Array]$dimensions
)
if ($idx.Length -ne $dimensions.Length) {
throw "Matrix index query length ($($idx.Length)) must be the same as dimension length ($($dimensions.Length))"
}
$stride = 1
# Commented out does lookup with wrap handling
# $index = $idx[$idx.Length-1] % $dimensions[$idx.Length-1]
$index = $idx[$idx.Length-1]
for ($i = $dimensions.Length-1; $i -ge 1; $i--) {
$stride *= $dimensions[$i]
# Commented out does lookup with wrap handling
# $index += ($idx[$i-1] % $dimensions[$i-1]) * $stride
$index += $idx[$i-1] * $stride
}
return $index
}
function GetNdMatrixElement
{
param(
[ValidateNotNullOrEmpty()]
[Array]$idx,
[ValidateNotNullOrEmpty()]
[Array]$matrix,
[ValidateNotNullOrEmpty()]
[Array]$dimensions
)
$arrayIndex = GetNdMatrixArrayIndex $idx $dimensions
return $matrix[$arrayIndex]
}
function GetNdMatrixIndex
{
param(
[int]$index,
[ValidateNotNullOrEmpty()]
[Array]$dimensions
)
$matrixIndex = @()
$stride = 1
for ($i = $dimensions.Length-1; $i -ge 1; $i--) {
$stride *= $dimensions[$i]
$page = [math]::floor($index / $stride) % $dimensions[$i-1]
$matrixIndex = ,$page + $matrixIndex
}
$col = $index % $dimensions[$dimensions.Length-1]
$matrixIndex += $col
return $matrixIndex
}
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# The below functions are non-dynamic examples that #
# help explain the above N-dimensional algorithm #
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
function Get4dMatrixElement([Array]$idx, [Array]$matrix, [Array]$dimensions)
{
$stride1 = $idx[0] * $dimensions[1] * $dimensions[2] * $dimensions[3]
$stride2 = $idx[1] * $dimensions[2] * $dimensions[3]
$stride3 = $idx[2] * $dimensions[3]
$stride4 = $idx[3]
return $matrix[$stride1 + $stride2 + $stride3 + $stride4]
}
function Get4dMatrixIndex([int]$index, [Array]$dimensions)
{
$stride1 = $dimensions[3]
$stride2 = $dimensions[2]
$stride3 = $dimensions[1]
$page1 = [math]::floor($index / $stride1) % $dimensions[2]
$page2 = [math]::floor($index / ($stride1 * $stride2)) % $dimensions[1]
$page3 = [math]::floor($index / ($stride1 * $stride2 * $stride3)) % $dimensions[0]
$remainder = $index % $dimensions[3]
return @($page3, $page2, $page1, $remainder)
}
|