-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConformance.ps1
More file actions
1606 lines (1279 loc) · 48.2 KB
/
Copy pathConformance.ps1
File metadata and controls
1606 lines (1279 loc) · 48.2 KB
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$ErrorActionPreference = "Stop"
# Prevent .NET first-run output from polluting captured JSON.
$env:DOTNET_NOLOGO = "true"
$env:DOTNET_CLI_TELEMETRY_OPTOUT = "true"
$script:ConformanceVersionCache = $null
<#
.SYNOPSIS
Fetches and refreshes Git tags for the current repository.
.DESCRIPTION
Fetches tags from origin and automatically handles shallow repositories by
unshallowing before fetching tags.
#>
function Update-ConformanceTags {
[CmdletBinding()]
param()
$isShallowRepository = & git rev-parse --is-shallow-repository 2>$null
if ($LASTEXITCODE -eq 0 -and $isShallowRepository -match '^true$') {
git fetch --unshallow --tags --force
}
else {
git fetch --tags --force
}
if ($LASTEXITCODE -ne 0) {
throw "Unable to fetch Git tags."
}
}
<#
.SYNOPSIS
Resolves the best available main branch reference.
.DESCRIPTION
Returns origin/main when available, otherwise main. Returns null when neither
reference exists.
#>
function Resolve-MainReference {
[CmdletBinding()]
param()
foreach ($candidateMainReference in @("origin/main", "main")) {
& git rev-parse --verify --quiet $candidateMainReference *> $null
if ($LASTEXITCODE -eq 0) {
return $candidateMainReference
}
}
return $null
}
<#
.SYNOPSIS
Installs PowerShell dependencies required by conformance tooling.
.DESCRIPTION
Ensures the powershell-yaml module is available for the current user.
#>
function Install-ConformanceDependencies {
[CmdletBinding()]
param()
$moduleName = "powershell-yaml"
if (-not (Get-Module -ListAvailable -Name $moduleName)) {
Write-Host "Installing PowerShell module '$moduleName'..."
Install-Module $moduleName -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop
}
if (-not (Get-Module -ListAvailable -Name $moduleName)) {
throw "PowerShell module '$moduleName' is not available after installation."
}
Write-Host "PowerShell module '$moduleName' is available."
}
<#
.SYNOPSIS
Imports YAML support for conformance scripts.
.DESCRIPTION
Validates that powershell-yaml is installed and imports it into the current
session.
#>
function Import-YamlSupport {
[CmdletBinding()]
param()
$moduleName = "powershell-yaml"
if (-not (Get-Module -ListAvailable -Name $moduleName)) {
throw @"
PowerShell module '$moduleName' is required.
Install it with:
Install-ConformanceDependencies
or:
Install-Module $moduleName -Scope CurrentUser
"@
}
Import-Module $moduleName -ErrorAction Stop
}
<#
.SYNOPSIS
Converts a glob-style pattern to a regular expression.
.PARAMETER Pattern
Glob pattern to convert. Supports *, **, and ? tokens.
.OUTPUTS
System.String
#>
function Convert-GlobPatternToRegex {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $Pattern
)
$normalized = $Pattern.Replace('\', '/').Trim()
if ([string]::IsNullOrWhiteSpace($normalized)) {
return $null
}
$escaped = [Regex]::Escape($normalized)
$escaped = $escaped.Replace('\*\*', '__DOUBLE_STAR__')
$escaped = $escaped.Replace('\*', '[^/]*')
$escaped = $escaped.Replace('\?', '[^/]')
$escaped = $escaped.Replace('__DOUBLE_STAR__', '.*')
return "^$escaped$"
}
<#
.SYNOPSIS
Tests whether a relative file path matches exclusion patterns.
.PARAMETER RelativePath
Path relative to the conformance root.
.PARAMETER Exclude
List of glob patterns used to exclude files.
.OUTPUTS
System.Boolean
#>
function Test-ConformanceExclude {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $RelativePath,
[Parameter(Mandatory)]
[string[]] $Exclude
)
$normalizedPath = $RelativePath.Replace('\', '/').TrimStart('/')
$fileName = [System.IO.Path]::GetFileName($normalizedPath)
foreach ($rawPattern in $Exclude) {
if ([string]::IsNullOrWhiteSpace($rawPattern)) {
continue
}
$pattern = $rawPattern.Replace('\', '/').Trim()
$isRootOnly = $pattern.StartsWith('/')
if ($isRootOnly) {
$pattern = $pattern.TrimStart('/')
if ($normalizedPath.Contains('/')) {
continue
}
$regex = Convert-GlobPatternToRegex -Pattern $pattern
if ($null -ne $regex -and $normalizedPath -match $regex) {
return $true
}
continue
}
if ($pattern.Contains('/')) {
$regex = Convert-GlobPatternToRegex -Pattern $pattern
if ($null -ne $regex -and $normalizedPath -match $regex) {
return $true
}
continue
}
$regex = Convert-GlobPatternToRegex -Pattern $pattern
if ($null -ne $regex -and $fileName -match $regex) {
return $true
}
}
return $false
}
<#
.SYNOPSIS
Normalizes exclusion patterns by removing empty entries.
.PARAMETER Exclude
Raw exclusion patterns.
.OUTPUTS
System.String[]
#>
function Get-ConformanceEffectiveExclude {
[CmdletBinding()]
param(
[string[]] $Exclude
)
return @(
$Exclude |
Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
)
}
<#
.SYNOPSIS
Writes scope diagnostics for a conformance operation.
.PARAMETER Title
Operation title shown in logs.
.PARAMETER InputPath
Path value received by the function.
.PARAMETER ResolvedPath
Absolute resolved path used by the function.
.PARAMETER Exclude
Effective exclusion patterns applied during the operation.
#>
function Write-ConformanceScope {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $Title,
[Parameter(Mandatory)]
[string] $InputPath,
[Parameter(Mandatory)]
[string] $ResolvedPath,
[Parameter(Mandatory)]
[string[]] $Exclude
)
Write-Host ("{0} scope:" -f $Title) -ForegroundColor DarkCyan
Write-Host (" input-path : '{0}'" -f $InputPath) -ForegroundColor DarkCyan
Write-Host (" resolved-path : '{0}'" -f $ResolvedPath) -ForegroundColor DarkCyan
if ($Exclude.Count -gt 0) {
Write-Host (" exclusions : {0} pattern(s)" -f $Exclude.Count) -ForegroundColor DarkCyan
foreach ($pattern in $Exclude) {
Write-Host (" - {0}" -f $pattern) -ForegroundColor DarkCyan
}
}
else {
Write-Host " exclusions : <none>" -ForegroundColor DarkCyan
}
}
function Resolve-GitPathSpec {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $ResolvedPath,
[Parameter(Mandatory)]
[string] $InputPath
)
$repositoryRoot = (& git rev-parse --show-toplevel 2>$null)
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($repositoryRoot)) {
throw "Unable to resolve the Git repository root."
}
$repositoryRoot = [System.IO.Path]::GetFullPath($repositoryRoot.Trim())
$resolvedFullPath = [System.IO.Path]::GetFullPath($ResolvedPath)
$repositoryRootWithSeparator = $repositoryRoot.TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar
$pathComparison = [System.StringComparison]::OrdinalIgnoreCase
if (
-not [string]::Equals($resolvedFullPath, $repositoryRoot, $pathComparison) -and
-not $resolvedFullPath.StartsWith($repositoryRootWithSeparator, $pathComparison)
) {
throw "Path '$InputPath' resolves outside the Git worktree and cannot be converted to a Git pathspec."
}
$relativePath = [System.IO.Path]::GetRelativePath(
$repositoryRoot,
$resolvedFullPath
).Replace('\', '/').Trim()
if ($relativePath -eq '.') {
return ''
}
return $relativePath.Trim('/')
}
<#
.SYNOPSIS
Builds a conformance manifest file from discovered YAML test content.
.DESCRIPTION
Discovers conformance YAML files, computes manifest metadata, and renders the
manifest by applying the Scriban template with didot-cli.
.PARAMETER Version
Conformance version to include in the manifest.
.PARAMETER CommitSha
Commit SHA used for manifest source revision.
.PARAMETER Path
Root directory of conformance files.
.PARAMETER Exclude
Glob patterns used to exclude files from manifest discovery.
.PARAMETER OutputFilePath
Manifest output file path. Relative values are resolved from Path.
.OUTPUTS
PSCustomObject
#>
function Build-ConformanceManifest {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $Version,
[Parameter(Mandatory)]
[string] $CommitSha,
[string] $Path = "conformance",
[string[]] $Exclude = @("bin/**", "/*.yaml", "/*.yml"),
[Alias("OutputPath")]
[string] $OutputFilePath = "bin/conformance.manifest.yaml"
)
$resolvedPath = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path
$resolvedOutputFilePath = if ([System.IO.Path]::IsPathRooted($OutputFilePath)) {
$OutputFilePath
}
else {
Join-Path $resolvedPath $OutputFilePath
}
$effectiveExclude = Get-ConformanceEffectiveExclude -Exclude $Exclude
$templatePath = Join-Path $resolvedPath "conformance.manifest.template.yaml"
if (-not (Test-Path -LiteralPath $templatePath -PathType Leaf)) {
throw "Conformance manifest template '$templatePath' was not found."
}
$didotInstalled = @(
dotnet tool list --local 2>$null |
Where-Object { $_ -match '^didot-cli\s' }
).Count -gt 0
if (-not $didotInstalled) {
throw @"
didot-cli local tool is required to build conformance manifest.
Install/restore it with:
dotnet tool restore
"@
}
$didotProbeOutput = @(& dotnet tool run didot --help 2>&1)
if ($LASTEXITCODE -ne 0) {
$probeText = $didotProbeOutput -join [Environment]::NewLine
throw @"
didot-cli local tool is declared but not runnable.
Run:
dotnet tool restore
Output:
$probeText
"@
}
Import-YamlSupport
$allYamlFiles = @(
Get-ChildItem `
-LiteralPath $resolvedPath `
-Recurse `
-File |
Where-Object {
$_.Extension -in @(".yaml", ".yml")
}
)
$selectedYamlFiles = @(
$allYamlFiles |
Where-Object {
$relativePath = [System.IO.Path]::GetRelativePath(
$resolvedPath,
$_.FullName
).Replace('\', '/')
(-not (Test-ConformanceExclude -RelativePath $relativePath -Exclude $effectiveExclude)) -and
$relativePath.Contains('/')
}
)
$patternSet = New-Object System.Collections.Generic.HashSet[string] ([System.StringComparer]::OrdinalIgnoreCase)
$testCount = 0
$testCaseCount = 0
foreach ($file in $selectedYamlFiles) {
$relativePath = [System.IO.Path]::GetRelativePath(
$resolvedPath,
$file.FullName
).Replace('\', '/')
if ($relativePath.Contains('/')) {
$topFolder = $relativePath.Split('/')[0]
if (-not [string]::IsNullOrWhiteSpace($topFolder)) {
[void]$patternSet.Add("$topFolder/**/*.yaml")
}
}
$yamlText = Get-Content -LiteralPath $file.FullName -Raw
if ([string]::IsNullOrWhiteSpace($yamlText)) {
continue
}
$yamlDocument = ConvertFrom-Yaml -Yaml $yamlText
$tests = @(
$yamlDocument.tests |
Where-Object { $null -ne $_ }
)
$testCount += $tests.Count
foreach ($test in $tests) {
$cases = @(
$test.cases |
Where-Object { $null -ne $_ }
)
$testCaseCount += $cases.Count
}
}
$patterns = @([System.Linq.Enumerable]::ToArray($patternSet) | Sort-Object)
$manifestTag = "conformance-$Version"
$tagReference = "refs/tags/$manifestTag"
$tagRevision = (& git rev-list -n 1 $tagReference 2>$null)
$revision = if ($LASTEXITCODE -eq 0 -and -not [string]::IsNullOrWhiteSpace($tagRevision)) {
$tagRevision.Trim()
}
elseif ([string]::IsNullOrWhiteSpace($CommitSha)) {
"<unknown>"
}
else {
$CommitSha.Trim()
}
$repository = if ([string]::IsNullOrWhiteSpace($env:APPVEYOR_REPO_NAME)) {
"https://github.com/Seddryck/Expressif"
}
else {
"https://github.com/$($env:APPVEYOR_REPO_NAME.Trim())"
}
$model = [ordered]@{
suite = [ordered]@{
version = $Version
}
source = [ordered]@{
repository = $repository
revision = $revision
tag = $manifestTag
}
contents = [ordered]@{
patterns = $patterns
counts = [ordered]@{
files = $selectedYamlFiles.Count
tests = $testCount
testCases = $testCaseCount
}
}
} | ConvertTo-Json -Depth 20
$outputDirectory = Split-Path -Path $resolvedOutputFilePath -Parent
if (-not [string]::IsNullOrWhiteSpace($outputDirectory)) {
New-Item -ItemType Directory -Path $outputDirectory -Force | Out-Null
}
$model | dotnet tool run didot `
-t $templatePath `
-e scriban `
-i `
-r json `
-o $resolvedOutputFilePath `
if ($LASTEXITCODE -ne 0) {
throw "Didot execution failed while building conformance manifest."
}
return [PSCustomObject]@{
ManifestPath = [System.IO.Path]::GetFullPath($resolvedOutputFilePath)
Version = $Version
Tag = $manifestTag
Revision = $revision
PatternCount = $patterns.Count
FileCount = $selectedYamlFiles.Count
TestCount = $testCount
TestCaseCount = $testCaseCount
}
}
<#
.SYNOPSIS
Validates conformance YAML files against schema and uniqueness rules.
.DESCRIPTION
Runs JSON schema validation using ajv-cli and checks for duplicate test and
case identifiers across selected YAML files.
.PARAMETER Path
Root directory of conformance files.
.PARAMETER Exclude
Glob patterns used to exclude files from validation.
.PARAMETER FailOnError
Throws when one or more violations are detected.
.OUTPUTS
System.Int32
#>
function Validate-Conformance {
[CmdletBinding()]
param(
[string] $Path = "conformance",
[string[]] $Exclude = @("bin/**", "/*.yaml", "/*.yml"),
[switch] $FailOnError
)
Write-Host "=== Validation ===" -ForegroundColor Cyan
$resolvedPath = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path
if (-not (Test-Path -LiteralPath $resolvedPath -PathType Container)) {
throw "Conformance directory '$Path' does not exist."
}
$schemaPath = Join-Path $resolvedPath "conformance.schema.json"
if (-not (Test-Path -LiteralPath $schemaPath -PathType Leaf)) {
throw "Conformance schema file '$schemaPath' was not found."
}
Import-YamlSupport
$npx = Get-Command "npx" -ErrorAction SilentlyContinue
if ($null -eq $npx) {
throw "'npx' was not found. Install Node.js to validate YAML files against the JSON schema."
}
$allYamlFiles = @(
Get-ChildItem `
-LiteralPath $resolvedPath `
-Recurse `
-File |
Where-Object {
$_.Extension -in @(".yaml", ".yml")
}
)
$candidateFiles = @(
$allYamlFiles |
Where-Object {
$relativePath = [System.IO.Path]::GetRelativePath(
$resolvedPath,
$_.FullName
).Replace('\', '/')
-not (Test-ConformanceExclude -RelativePath $relativePath -Exclude $Exclude)
}
)
$testedCount = $candidateFiles.Count
$excludedCount = $allYamlFiles.Count - $testedCount
$schemaFailureCount = 0
$duplicateTestIdCount = 0
$duplicateCaseIdCount = 0
$validatedTestIdCount = 0
$validatedCaseIdCount = 0
$selectionRate = if ($allYamlFiles.Count -eq 0) {
"0.00"
}
else {
(($testedCount / [double]$allYamlFiles.Count) * 100).ToString(
"F2",
[System.Globalization.CultureInfo]::InvariantCulture
)
}
$effectiveExclude = Get-ConformanceEffectiveExclude -Exclude $Exclude
Write-ConformanceScope `
-Title "Validation" `
-InputPath $Path `
-ResolvedPath $resolvedPath `
-Exclude $effectiveExclude
Write-Host "Validation discovery:" -ForegroundColor DarkCyan
Write-Host (" yaml-found : {0}" -f $allYamlFiles.Count) -ForegroundColor DarkCyan
Write-Host (" yaml-selected : {0}" -f $testedCount) -ForegroundColor DarkCyan
Write-Host (" yaml-excluded : {0}" -f $excludedCount) -ForegroundColor DarkCyan
Write-Host (" selection-rate : {0}%" -f $selectionRate) -ForegroundColor DarkCyan
$entriesToValidate = @()
$parsedEntries = @()
$tempDirectory = Join-Path ([System.IO.Path]::GetTempPath()) ("expressif-conformance-" + [Guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Path $tempDirectory -Force | Out-Null
if ($testedCount -eq 0) {
Write-Warning "No conformance YAML files were considered for validation in '$resolvedPath'."
}
try {
$index = 0
foreach ($file in $candidateFiles) {
$relativePath = [System.IO.Path]::GetRelativePath(
$resolvedPath,
$file.FullName
).Replace('\', '/')
try {
$yamlText = Get-Content -LiteralPath $file.FullName -Raw
if ([string]::IsNullOrWhiteSpace($yamlText)) {
throw "YAML file is empty."
}
$yamlDocument = ConvertFrom-Yaml -Yaml $yamlText
$jsonDocument = $yamlDocument | ConvertTo-Json -Depth 100
$jsonPath = Join-Path $tempDirectory ("case-{0:0000}.json" -f $index)
Set-Content -LiteralPath $jsonPath -Value $jsonDocument -Encoding UTF8
$entriesToValidate += [PSCustomObject]@{
RelativePath = $relativePath
JsonPath = [System.IO.Path]::GetFullPath($jsonPath)
}
$parsedEntries += [PSCustomObject]@{
RelativePath = $relativePath
Document = $yamlDocument
}
$index++
}
catch {
$schemaFailureCount++
Write-Warning "Schema validation failed for '$relativePath'."
}
}
$chunkSize = 40
for ($offset = 0; $offset -lt $entriesToValidate.Count; $offset += $chunkSize) {
$chunk = @($entriesToValidate | Select-Object -Skip $offset -First $chunkSize)
$statusByJsonPath = @{}
foreach ($entry in $chunk) {
$statusByJsonPath[$entry.JsonPath] = $false
}
$arguments = @(
"--yes",
"ajv-cli",
"validate",
"--spec=draft2020",
"-s",
$schemaPath
)
foreach ($entry in $chunk) {
$arguments += @("-d", $entry.JsonPath)
}
$validationOutput = @(& $npx.Source @arguments 2>&1)
foreach ($line in $validationOutput) {
$text = "$line"
if ($text -match '^(?<path>.+?)\s+(?<result>valid|invalid)$') {
$jsonPath = [System.IO.Path]::GetFullPath($Matches.path.Trim())
$statusByJsonPath[$jsonPath] = ($Matches.result -eq "valid")
}
}
foreach ($entry in $chunk) {
if (-not $statusByJsonPath[$entry.JsonPath]) {
$schemaFailureCount++
Write-Warning "Schema validation failed for '$($entry.RelativePath)'."
}
}
}
$seenTestIds = @{}
$seenCaseIds = @{}
foreach ($entry in $parsedEntries) {
$tests = @($entry.Document.tests)
foreach ($test in $tests) {
if ($null -eq $test) {
continue
}
$testId = [string]$test.id
if (-not [string]::IsNullOrWhiteSpace($testId)) {
$validatedTestIdCount++
if ($seenTestIds.ContainsKey($testId)) {
$duplicateTestIdCount++
Write-Warning (
"Duplicate test id '{0}' first seen in '{1}', duplicated in '{2}'." -f
$testId,
$seenTestIds[$testId],
$entry.RelativePath
)
}
else {
$seenTestIds[$testId] = $entry.RelativePath
}
}
$cases = @($test.cases)
foreach ($case in $cases) {
if ($null -eq $case) {
continue
}
$caseId = [string]$case.id
if (-not [string]::IsNullOrWhiteSpace($caseId)) {
$validatedCaseIdCount++
if ($seenCaseIds.ContainsKey($caseId)) {
$duplicateCaseIdCount++
Write-Warning (
"Duplicate case id '{0}' first seen in '{1}', duplicated in '{2}'." -f
$caseId,
$seenCaseIds[$caseId],
$entry.RelativePath
)
}
else {
$seenCaseIds[$caseId] = $entry.RelativePath
}
}
}
}
}
}
finally {
if (Test-Path -LiteralPath $tempDirectory) {
Remove-Item -LiteralPath $tempDirectory -Recurse -Force
}
}
$schemaSuccessfulCount = $testedCount - $schemaFailureCount
$totalFailureCount = $schemaFailureCount + $duplicateTestIdCount + $duplicateCaseIdCount
$schemaSummary = (
"Schema validation summary: tested={0}; successful={1}; failed={2}" -f
$testedCount,
$schemaSuccessfulCount,
$schemaFailureCount
)
$uniquenessSummary = (
"Uniqueness summary: test-ids-validated={0}; duplicate-test-ids={1}; case-ids-validated={2}; duplicate-case-ids={3}" -f
$validatedTestIdCount,
$duplicateTestIdCount,
$validatedCaseIdCount,
$duplicateCaseIdCount
)
$globalSummary = (
"Conformance validation summary: total-violations={0}" -f
$totalFailureCount
)
$schemaPass = ($schemaFailureCount -eq 0)
$uniquenessPass = (($duplicateTestIdCount + $duplicateCaseIdCount) -eq 0)
$globalPass = ($totalFailureCount -eq 0)
$schemaColor = if ($schemaPass) { "Green" } else { "Red" }
$uniquenessColor = if ($uniquenessPass) { "Green" } else { "Red" }
$globalColor = if ($globalPass) { "Green" } else { "Red" }
$schemaStatus = if ($schemaPass) { "PASS" } else { "FAIL" }
$uniquenessStatus = if ($uniquenessPass) { "PASS" } else { "FAIL" }
$globalStatus = if ($globalPass) { "PASS" } else { "FAIL" }
Write-Host ("[{0}] {1}" -f $schemaStatus, $schemaSummary) -ForegroundColor $schemaColor
Write-Host ("[{0}] {1}" -f $uniquenessStatus, $uniquenessSummary) -ForegroundColor $uniquenessColor
Write-Host ("[{0}] {1}" -f $globalStatus, $globalSummary) -ForegroundColor $globalColor
if ($FailOnError -and $totalFailureCount -gt 0) {
throw (
"Conformance validation failed with {0} violation(s): schema={1}; duplicate-test-ids={2}; duplicate-case-ids={3}." -f
$totalFailureCount,
$schemaFailureCount,
$duplicateTestIdCount,
$duplicateCaseIdCount
)
}
return [int]$totalFailureCount
}
<#
.SYNOPSIS
Calculates the conformance version from Git history and tags.
.DESCRIPTION
Uses GitVersion with conformance-specific configuration and reuses the latest
conformance release version when no selected conformance files changed.
.PARAMETER Path
Root directory used to detect conformance file changes.
.PARAMETER Exclude
Glob patterns used to exclude changed files from version-impact detection.
.PARAMETER Configuration
GitVersion configuration file path.
.PARAMETER Warn
Emits additional warnings for tag visibility conditions.
.PARAMETER Refresh
Bypasses cached value and recalculates the version.
.PARAMETER NoEnv
Skips writing the GitVersion_Conformance_SemVer environment variable.
.OUTPUTS
System.String
#>
function Get-ConformanceVersion {
[CmdletBinding()]
param(
[Alias("ConformancePath")]
[string] $Path = "conformance",
[string[]] $Exclude = @("bin/**"),
[string] $Configuration = "GitVersion.Conformance.yml",
[switch] $Warn,
[switch] $Refresh,
[switch] $NoEnv
)
Write-Host "=== Calculating conformance version ==="
if (-not $Refresh -and -not [string]::IsNullOrWhiteSpace($script:ConformanceVersionCache)) {
$conformanceVersion = $script:ConformanceVersionCache
Write-Host "Conformance version (cached): $conformanceVersion"
if (-not $NoEnv) {
$env:GitVersion_Conformance_SemVer = "conformance-$conformanceVersion"
Write-Host (
"Environment variable GitVersion_Conformance_SemVer: {0}" -f
$env:GitVersion_Conformance_SemVer
)
}
return $conformanceVersion
}
Update-ConformanceTags
$resolvedPath = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path
$effectiveExclude = Get-ConformanceEffectiveExclude -Exclude $Exclude
$pathSpec = Resolve-GitPathSpec -ResolvedPath $resolvedPath -InputPath $Path
if ([string]::IsNullOrWhiteSpace($pathSpec)) {
throw "Path '$Path' cannot be converted to a Git pathspec."
}
$versionedCommit = if (-not [string]::IsNullOrWhiteSpace($env:APPVEYOR_REPO_COMMIT)) {
$env:APPVEYOR_REPO_COMMIT.Trim()
}
else {
(& git rev-parse HEAD 2>$null)
}
$versionedCommit =
if ($null -eq $versionedCommit) { "" } else { $versionedCommit.Trim() }
$changedConformanceFiles = @()
if (-not [string]::IsNullOrWhiteSpace($versionedCommit)) {
$changedConformanceFiles = @(
git diff-tree --no-commit-id --name-only -r $versionedCommit -- "$pathSpec/" |
Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
)
}
$selectedChangedConformanceFiles = @(
$changedConformanceFiles |
Where-Object {
$normalizedPath = $_.Replace('\', '/').TrimStart('/')
$prefix = "$pathSpec/"
if (-not $normalizedPath.StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)) {
return $false
}
$relativePath = $normalizedPath.Substring($prefix.Length)
-not (Test-ConformanceExclude -RelativePath $relativePath -Exclude $effectiveExclude)
}
)
Write-Host "Conformance changes for version calculation:" -ForegroundColor DarkCyan
Write-Host (" input-path : '{0}'" -f $Path) -ForegroundColor DarkCyan
Write-Host (" resolved-path : '{0}'" -f $resolvedPath) -ForegroundColor DarkCyan
Write-Host (" git-pathspec : '{0}/'" -f $pathSpec) -ForegroundColor DarkCyan
if ($effectiveExclude.Count -gt 0) {
Write-Host (" exclusions : {0} pattern(s)" -f $effectiveExclude.Count) -ForegroundColor DarkCyan
foreach ($pattern in $effectiveExclude) {
Write-Host (" - {0}" -f $pattern) -ForegroundColor DarkCyan
}
}
else {
Write-Host " exclusions : <none>" -ForegroundColor DarkCyan
}
Write-Host (" commit-sha : '{0}'" -f $versionedCommit) -ForegroundColor DarkCyan
Write-Host (" files-found : {0}" -f $changedConformanceFiles.Count) -ForegroundColor DarkCyan
Write-Host (" files-selected : {0}" -f $selectedChangedConformanceFiles.Count) -ForegroundColor DarkCyan
Write-Host (" files-excluded : {0}" -f ($changedConformanceFiles.Count - $selectedChangedConformanceFiles.Count)) -ForegroundColor DarkCyan
if ($selectedChangedConformanceFiles.Count -gt 0) {
$selectedChangedConformanceFiles |
Sort-Object |
ForEach-Object {
Write-Host (" - {0}" -f $_) -ForegroundColor DarkCyan
}
}
else {
Write-Host " - <none>" -ForegroundColor DarkCyan
}
$currentYear = [int](Get-Date -Format "yyyy")
$currentMonth = [int](Get-Date -Format "MM")
$calendarBaseVersion = "$currentYear.$currentMonth.0"
$tagPattern =
"^conformance-(?<year>\d{4})\.(?<month>\d{1,2})\.(?<patch>\d+)$"
$mainReference = Resolve-MainReference
if ($null -ne $mainReference) {
$conformanceTags =
git tag --merged $mainReference --list "conformance-*.*.*"
if ($Warn) {
$unreachableConformanceTags =
git tag --no-merged $mainReference --list "conformance-*.*.*"
if ($unreachableConformanceTags) {
Write-Warning (
"Ignoring conformance tags not reachable from " +