forked from benclaussen/NetboxPS
-
Notifications
You must be signed in to change notification settings - Fork 4
1024 lines (878 loc) · 43.4 KB
/
pre-release-validation.yml
File metadata and controls
1024 lines (878 loc) · 43.4 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
# Pre-Release Validation v2.1
# ============================
# Comprehensive test suite for release candidates
#
# This workflow runs EVERYTHING before a release:
# - Unit tests on all platforms (Ubuntu, Windows, macOS)
# - Unit tests on all PowerShell versions (5.1, 7.x)
# - Code coverage analysis with threshold enforcement
# - Integration tests against all supported Netbox versions
# - PSScriptAnalyzer code quality checks
# - Documentation completeness validation
# - Breaking change detection vs PSGallery release
# - Module import verification
# - Generates a comprehensive release readiness report
#
# Trigger: Manual only (workflow_dispatch)
# Duration: ~12-15 minutes
# Use: Before merging to main / creating a release
name: Pre-Release Validation
on:
workflow_dispatch:
inputs:
version:
description: 'Version being validated (e.g., 4.5.0)'
required: true
type: string
skip_integration:
description: 'Skip integration tests (faster, unit tests only)'
required: false
default: false
type: boolean
coverage_threshold:
description: 'Minimum code coverage percentage (default: 70)'
required: false
default: '70'
type: string
env:
NETBOX_TOKEN: "0123456789abcdef0123456789abcdef01234567"
COMPOSE_PROJECT_NAME: "powernetbox"
permissions:
contents: read
jobs:
# ============================================================
# Stage 1: Unit Tests - Full Platform Matrix
# ============================================================
unit-tests:
name: Unit [${{ matrix.os }}, ${{ matrix.pwsh && 'PS7' || 'PS5.1' }}]
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
pwsh: [true]
include:
- os: windows-latest
pwsh: false
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies (pwsh)
if: matrix.pwsh
shell: pwsh
run: |
if (-not (Get-PSRepository -Name PSGallery -ErrorAction SilentlyContinue)) {
Register-PSRepository -Default
}
Set-PSRepository PSGallery -InstallationPolicy Trusted
Install-Module Pester -Force -Scope CurrentUser -MinimumVersion 5.0.0
Install-Module PSScriptAnalyzer -Force -Scope CurrentUser
- name: Install dependencies (powershell 5.1)
if: '!matrix.pwsh'
shell: powershell
run: |
if (-not (Get-PSRepository -Name PSGallery -ErrorAction SilentlyContinue)) {
Register-PSRepository -Default
}
Set-PSRepository PSGallery -InstallationPolicy Trusted
Install-Module Pester -Force -Scope CurrentUser -MinimumVersion 5.0.0
Install-Module PSScriptAnalyzer -Force -Scope CurrentUser
- name: Build module (pwsh)
if: matrix.pwsh
shell: pwsh
run: ./deploy.ps1 -Environment dev -SkipVersion
- name: Build module (powershell 5.1)
if: '!matrix.pwsh'
shell: powershell
run: ./deploy.ps1 -Environment dev -SkipVersion
- name: Run unit tests (pwsh)
if: matrix.pwsh
shell: pwsh
run: |
$config = New-PesterConfiguration
$config.Run.Path = './Tests/*.Tests.ps1'
$config.Run.Exit = $true
$config.Filter.ExcludeTag = @('Integration', 'Live')
$config.TestResult.Enabled = $true
$config.TestResult.OutputPath = 'TestResults.xml'
$config.TestResult.OutputFormat = 'NUnitXml'
$config.Output.Verbosity = 'Normal'
Invoke-Pester -Configuration $config
- name: Run unit tests (powershell 5.1)
if: '!matrix.pwsh'
shell: powershell
run: |
$config = New-PesterConfiguration
$config.Run.Path = './Tests/*.Tests.ps1'
$config.Run.Exit = $true
$config.Filter.ExcludeTag = @('Integration', 'Live')
$config.TestResult.Enabled = $true
$config.TestResult.OutputPath = 'TestResults.xml'
$config.TestResult.OutputFormat = 'NUnitXml'
$config.Output.Verbosity = 'Normal'
Invoke-Pester -Configuration $config
- name: Upload test results
uses: actions/upload-artifact@v4
if: always()
with:
name: unit-tests-${{ matrix.os }}-${{ matrix.pwsh && 'ps7' || 'ps51' }}
path: TestResults.xml
retention-days: 30
# ============================================================
# Stage 2: Code Coverage Analysis
# ============================================================
code-coverage:
name: Code Coverage
runs-on: ubuntu-latest
outputs:
coverage_percent: ${{ steps.coverage.outputs.coverage_percent }}
covered_commands: ${{ steps.coverage.outputs.covered_commands }}
total_commands: ${{ steps.coverage.outputs.total_commands }}
missed_functions: ${{ steps.coverage.outputs.missed_functions }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies
shell: pwsh
run: |
Set-PSRepository PSGallery -InstallationPolicy Trusted
Install-Module Pester -Force -Scope CurrentUser -MinimumVersion 5.0.0
- name: Build module
shell: pwsh
run: ./deploy.ps1 -Environment dev -SkipVersion
- name: Run tests with code coverage
id: coverage
shell: pwsh
run: |
Write-Host "=== Running Tests with Code Coverage ===" -ForegroundColor Cyan
Write-Host ""
# The module is built by concatenating all Functions/*.ps1 into PowerNetbox.psm1
# So we need to analyze coverage on the built module, not the source files
$moduleFile = './PowerNetbox/PowerNetbox.psm1'
if (-not (Test-Path $moduleFile)) {
Write-Host "ERROR: Built module not found at $moduleFile" -ForegroundColor Red
exit 1
}
$moduleSize = (Get-Item $moduleFile).Length / 1KB
Write-Host "Analyzing coverage for built module ($([math]::Round($moduleSize, 1)) KB)..." -ForegroundColor Yellow
$config = New-PesterConfiguration
$config.Run.Path = './Tests/*.Tests.ps1'
$config.Run.Exit = $false
$config.Run.PassThru = $true # REQUIRED for Invoke-Pester to return result object
$config.Filter.ExcludeTag = @('Integration', 'Live')
$config.Output.Verbosity = 'Normal'
# Enable code coverage on the built module file
$config.CodeCoverage.Enabled = $true
$config.CodeCoverage.Path = @($moduleFile)
$config.CodeCoverage.OutputPath = 'coverage.xml'
$config.CodeCoverage.OutputFormat = 'JaCoCo'
$result = Invoke-Pester -Configuration $config
# Get coverage metrics from result
$coverage = $result.CodeCoverage
$totalCommands = [int]$coverage.CommandsAnalyzedCount
$coveredCommands = [int]$coverage.CommandsExecutedCount
$missedCommands = [int]$coverage.CommandsMissedCount
$coveragePercent = [math]::Round($coverage.CoveragePercent, 2)
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " CODE COVERAGE RESULTS" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Coverage: $coveragePercent%" -ForegroundColor $(if ($coveragePercent -ge 70) { 'Green' } elseif ($coveragePercent -ge 50) { 'Yellow' } else { 'Red' })
Write-Host "Executed: $coveredCommands commands"
Write-Host "Analyzed: $totalCommands commands"
Write-Host "Missed: $missedCommands commands"
Write-Host ""
# Find uncovered function names by looking at the missed commands
# The concatenated module has #region markers we can use
$uncoveredFunctions = @()
if ($coverage.CommandsMissed) {
# Group missed commands by their function context
$uncoveredFunctions = $coverage.CommandsMissed |
Where-Object { $_.Function -and $_.Function -ne '<ScriptBlock>' } |
Group-Object Function |
Sort-Object Count -Descending |
Select-Object -First 10 -ExpandProperty Name
}
$missedFunctionsStr = if ($uncoveredFunctions.Count -gt 0) {
$uncoveredFunctions -join ', '
} else {
"All functions have some coverage"
}
if ($uncoveredFunctions.Count -gt 0) {
Write-Host "Functions with lowest coverage (by missed commands):" -ForegroundColor Yellow
$uncoveredFunctions | ForEach-Object {
Write-Host " - $_" -ForegroundColor Yellow
}
}
# Set outputs
"coverage_percent=$coveragePercent" >> $env:GITHUB_OUTPUT
"covered_commands=$coveredCommands" >> $env:GITHUB_OUTPUT
"total_commands=$totalCommands" >> $env:GITHUB_OUTPUT
"missed_functions=$missedFunctionsStr" >> $env:GITHUB_OUTPUT
# Export detailed report
@{
CoveragePercent = $coveragePercent
CoveredCommands = $coveredCommands
TotalCommands = $totalCommands
MissedCommands = $missedCommands
Threshold = ${{ inputs.coverage_threshold }}
UncoveredFunctions = $uncoveredFunctions
} | ConvertTo-Json -Depth 5 | Out-File "coverage-report.json"
# Check threshold
$threshold = [int]"${{ inputs.coverage_threshold }}"
if ($coveragePercent -lt $threshold) {
Write-Host ""
Write-Host "::warning::Code coverage ($coveragePercent%) is below threshold ($threshold%)"
}
- name: Upload coverage report
uses: actions/upload-artifact@v4
if: always()
with:
name: code-coverage
path: |
coverage.xml
coverage-report.json
retention-days: 30
# ============================================================
# Stage 3: Code Quality - PSScriptAnalyzer
# ============================================================
code-quality:
name: Code Quality
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install PSScriptAnalyzer
shell: pwsh
run: |
Set-PSRepository PSGallery -InstallationPolicy Trusted
Install-Module PSScriptAnalyzer -Force -Scope CurrentUser
- name: Run PSScriptAnalyzer
id: pssa
shell: pwsh
run: |
Write-Host "Running PSScriptAnalyzer on Functions/..." -ForegroundColor Cyan
$results = Invoke-ScriptAnalyzer -Path ./Functions -Recurse -Settings PSGallery
$errors = $results | Where-Object { $_.Severity -eq 'Error' }
$warnings = $results | Where-Object { $_.Severity -eq 'Warning' }
$info = $results | Where-Object { $_.Severity -eq 'Information' }
Write-Host ""
Write-Host "=== PSScriptAnalyzer Results ===" -ForegroundColor Cyan
Write-Host "Errors: $($errors.Count)" -ForegroundColor $(if ($errors.Count -gt 0) { 'Red' } else { 'Green' })
Write-Host "Warnings: $($warnings.Count)" -ForegroundColor $(if ($warnings.Count -gt 0) { 'Yellow' } else { 'Green' })
Write-Host "Info: $($info.Count)" -ForegroundColor Gray
if ($errors.Count -gt 0) {
Write-Host ""
Write-Host "=== Errors ===" -ForegroundColor Red
$errors | ForEach-Object {
Write-Host " $($_.ScriptName):$($_.Line) - $($_.RuleName): $($_.Message)" -ForegroundColor Red
}
}
$results | ConvertTo-Json | Out-File "pssa-results.json"
if ($errors.Count -gt 0) {
Write-Host ""
Write-Host "::error::PSScriptAnalyzer found $($errors.Count) error(s)"
exit 1
}
- name: Upload PSSA results
uses: actions/upload-artifact@v4
if: always()
with:
name: code-quality-pssa
path: pssa-results.json
retention-days: 30
# ============================================================
# Stage 4: Documentation Validation
# ============================================================
documentation-validation:
name: Documentation Validation
runs-on: ubuntu-latest
outputs:
total_functions: ${{ steps.docs.outputs.total_functions }}
documented_functions: ${{ steps.docs.outputs.documented_functions }}
documentation_percent: ${{ steps.docs.outputs.documentation_percent }}
missing_docs: ${{ steps.docs.outputs.missing_docs }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Validate documentation
id: docs
shell: pwsh
run: |
Write-Host "=== Validating Function Documentation ===" -ForegroundColor Cyan
Write-Host ""
# Build module first
./deploy.ps1 -Environment prod -SkipVersion
Import-Module ./PowerNetbox/PowerNetbox.psd1 -Force
# Get all public functions
$publicFunctions = Get-Command -Module PowerNetbox | Where-Object { $_.Name -match '-' }
Write-Host "Checking documentation for $($publicFunctions.Count) public functions..." -ForegroundColor Yellow
Write-Host ""
$results = @()
$missingDocs = @()
foreach ($func in $publicFunctions) {
$help = Get-Help $func.Name -ErrorAction SilentlyContinue
$hasSynopsis = $help.Synopsis -and
$help.Synopsis -ne $func.Name -and
$help.Synopsis -notmatch '^[\s\r\n]*$'
$hasDescription = $help.Description -and
$help.Description.Text -and
$help.Description.Text.Trim() -ne ''
$hasExamples = $help.Examples -and
$help.Examples.Example -and
$help.Examples.Example.Count -gt 0
$hasParameters = $true # Less strict on parameters
$isDocumented = $hasSynopsis -and $hasDescription -and $hasExamples
$results += [PSCustomObject]@{
Function = $func.Name
Synopsis = $hasSynopsis
Description = $hasDescription
Examples = $hasExamples
Documented = $isDocumented
}
if (-not $isDocumented) {
$missing = @()
if (-not $hasSynopsis) { $missing += "Synopsis" }
if (-not $hasDescription) { $missing += "Description" }
if (-not $hasExamples) { $missing += "Examples" }
$missingDocs += "$($func.Name) (missing: $($missing -join ', '))"
}
}
$totalFunctions = $results.Count
$documentedFunctions = ($results | Where-Object { $_.Documented }).Count
$documentationPercent = if ($totalFunctions -gt 0) {
[math]::Round(($documentedFunctions / $totalFunctions) * 100, 1)
} else { 0 }
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " DOCUMENTATION VALIDATION RESULTS" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Total functions: $totalFunctions"
Write-Host "Fully documented: $documentedFunctions"
Write-Host "Documentation: $documentationPercent%" -ForegroundColor $(if ($documentationPercent -ge 90) { 'Green' } elseif ($documentationPercent -ge 70) { 'Yellow' } else { 'Red' })
Write-Host ""
if ($missingDocs.Count -gt 0 -and $missingDocs.Count -le 20) {
Write-Host "Functions with incomplete documentation:" -ForegroundColor Yellow
$missingDocs | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
} elseif ($missingDocs.Count -gt 20) {
Write-Host "Functions with incomplete documentation: $($missingDocs.Count) functions" -ForegroundColor Yellow
Write-Host "(First 10 shown)" -ForegroundColor Gray
$missingDocs | Select-Object -First 10 | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
}
# Set outputs
$missingDocsStr = if ($missingDocs.Count -gt 0) {
($missingDocs | Select-Object -First 5) -join '; '
} else { "None" }
"total_functions=$totalFunctions" >> $env:GITHUB_OUTPUT
"documented_functions=$documentedFunctions" >> $env:GITHUB_OUTPUT
"documentation_percent=$documentationPercent" >> $env:GITHUB_OUTPUT
"missing_docs=$missingDocsStr" >> $env:GITHUB_OUTPUT
# Export full report
@{
TotalFunctions = $totalFunctions
DocumentedFunctions = $documentedFunctions
DocumentationPercent = $documentationPercent
MissingDocumentation = $missingDocs
Details = $results
} | ConvertTo-Json -Depth 5 | Out-File "documentation-report.json"
- name: Upload documentation report
uses: actions/upload-artifact@v4
with:
name: documentation-validation
path: documentation-report.json
retention-days: 30
# ============================================================
# Stage 5: Breaking Change Detection
# ============================================================
breaking-changes:
name: Breaking Change Detection
runs-on: ubuntu-latest
outputs:
removed_commands: ${{ steps.compare.outputs.removed_commands }}
added_commands: ${{ steps.compare.outputs.added_commands }}
removed_count: ${{ steps.compare.outputs.removed_count }}
added_count: ${{ steps.compare.outputs.added_count }}
has_breaking_changes: ${{ steps.compare.outputs.has_breaking_changes }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Compare with PSGallery release
id: compare
shell: pwsh
run: |
Write-Host "=== Breaking Change Detection ===" -ForegroundColor Cyan
Write-Host ""
# Build current module
Write-Host "Building current module..." -ForegroundColor Yellow
./deploy.ps1 -Environment prod -SkipVersion
Import-Module ./PowerNetbox/PowerNetbox.psd1 -Force -DisableNameChecking
$currentCommands = Get-Command -Module PowerNetbox |
Where-Object { $_.Name -match '-' } |
Select-Object -ExpandProperty Name |
Sort-Object
Write-Host "Current module has $($currentCommands.Count) commands"
# Try to get PSGallery version
Write-Host ""
Write-Host "Fetching latest PSGallery release..." -ForegroundColor Yellow
$galleryCommands = @()
try {
# Save to temp location
$tempPath = Join-Path $env:RUNNER_TEMP 'PSGalleryModule'
New-Item -ItemType Directory -Path $tempPath -Force | Out-Null
Save-Module -Name PowerNetbox -Path $tempPath -Repository PSGallery -ErrorAction Stop
# Find and import
$galleryManifest = Get-ChildItem -Path $tempPath -Filter 'PowerNetbox.psd1' -Recurse | Select-Object -First 1
if ($galleryManifest) {
Import-Module $galleryManifest.FullName -Force -DisableNameChecking -Prefix 'Gallery'
$galleryCommands = Get-Command -Module PowerNetbox |
Where-Object { $_.Name -match '-Gallery' } |
ForEach-Object { $_.Name -replace '-Gallery', '-' } |
Sort-Object
# Actually get commands without prefix trick
Remove-Module PowerNetbox -Force -ErrorAction SilentlyContinue
Import-Module $galleryManifest.FullName -Force -DisableNameChecking
$galleryCommands = Get-Command -Module PowerNetbox |
Where-Object { $_.Name -match '-' } |
Select-Object -ExpandProperty Name |
Sort-Object
$galleryVersion = (Get-Module PowerNetbox).Version
Write-Host "PSGallery version: $galleryVersion with $($galleryCommands.Count) commands" -ForegroundColor Green
# Reimport current
Remove-Module PowerNetbox -Force
Import-Module ./PowerNetbox/PowerNetbox.psd1 -Force -DisableNameChecking
}
} catch {
Write-Host "Could not fetch PSGallery module: $_" -ForegroundColor Yellow
Write-Host "Skipping breaking change detection (no baseline)" -ForegroundColor Yellow
}
# Compare
$removedCommands = @()
$addedCommands = @()
if ($galleryCommands.Count -gt 0) {
$removedCommands = $galleryCommands | Where-Object { $_ -notin $currentCommands }
$addedCommands = $currentCommands | Where-Object { $_ -notin $galleryCommands }
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " BREAKING CHANGE ANALYSIS" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
if ($removedCommands.Count -gt 0) {
Write-Host "⚠️ REMOVED COMMANDS (Breaking Changes): $($removedCommands.Count)" -ForegroundColor Red
$removedCommands | ForEach-Object { Write-Host " - $_" -ForegroundColor Red }
} else {
Write-Host "✅ No removed commands" -ForegroundColor Green
}
Write-Host ""
if ($addedCommands.Count -gt 0) {
Write-Host "➕ NEW COMMANDS: $($addedCommands.Count)" -ForegroundColor Green
if ($addedCommands.Count -le 20) {
$addedCommands | ForEach-Object { Write-Host " + $_" -ForegroundColor Green }
} else {
$addedCommands | Select-Object -First 10 | ForEach-Object { Write-Host " + $_" -ForegroundColor Green }
Write-Host " ... and $($addedCommands.Count - 10) more" -ForegroundColor Gray
}
} else {
Write-Host "No new commands" -ForegroundColor Gray
}
}
# Set outputs
$removedStr = if ($removedCommands.Count -gt 0) { ($removedCommands | Select-Object -First 5) -join ', ' } else { "None" }
$addedStr = if ($addedCommands.Count -gt 0) { ($addedCommands | Select-Object -First 5) -join ', ' } else { "None" }
$hasBreaking = if ($removedCommands.Count -gt 0) { "true" } else { "false" }
"removed_commands=$removedStr" >> $env:GITHUB_OUTPUT
"added_commands=$addedStr" >> $env:GITHUB_OUTPUT
"removed_count=$($removedCommands.Count)" >> $env:GITHUB_OUTPUT
"added_count=$($addedCommands.Count)" >> $env:GITHUB_OUTPUT
"has_breaking_changes=$hasBreaking" >> $env:GITHUB_OUTPUT
# Export report
@{
CurrentCommandCount = $currentCommands.Count
GalleryCommandCount = $galleryCommands.Count
RemovedCommands = $removedCommands
AddedCommands = $addedCommands
HasBreakingChanges = ($removedCommands.Count -gt 0)
} | ConvertTo-Json -Depth 5 | Out-File "breaking-changes-report.json"
- name: Upload breaking changes report
uses: actions/upload-artifact@v4
with:
name: breaking-changes
path: breaking-changes-report.json
retention-days: 30
# ============================================================
# Stage 6: Integration Tests - All Netbox Versions
# ============================================================
integration-tests:
name: Integration [Netbox ${{ matrix.netbox_short }}]
runs-on: ubuntu-latest
if: ${{ !inputs.skip_integration }}
needs: [unit-tests]
strategy:
fail-fast: false
matrix:
include:
# Minimum supported version
- netbox: "v4.3.7-3.3.0"
netbox_short: "4.3.7"
# Stable version
- netbox: "v4.4.10-3.4.2"
netbox_short: "4.4.10"
# Latest version (netbox-docker 4.0.2)
- netbox: "v4.5.8-4.0.2"
netbox_short: "4.5.8"
env:
NETBOX_VERSION: ${{ matrix.netbox }}
NETBOX_HOST: "localhost:8000"
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- name: Start Netbox ${{ matrix.netbox_short }}
run: |
echo "Starting Netbox ${{ matrix.netbox_short }}..."
docker compose -f docker-compose.ci.yml pull
docker compose -f docker-compose.ci.yml up -d
- name: Wait for Netbox
run: |
echo "Waiting for Netbox to be ready (may take 5-7 minutes for 4.5+ migrations)..."
MAX_WAIT=420
ELAPSED=0
while [ $ELAPSED -lt $MAX_WAIT ]; do
HEALTH=$(docker inspect --format='{{.State.Health.Status}}' powernetbox-netbox-1 2>/dev/null || echo "starting")
echo "[${ELAPSED}s] Status: $HEALTH"
if [ "$HEALTH" = "healthy" ]; then
curl -sf http://localhost:8000/login/ > /dev/null 2>&1 && exit 0
fi
[ "$HEALTH" = "unhealthy" ] && docker compose -f docker-compose.ci.yml logs netbox --tail 50 && exit 1
sleep 10
ELAPSED=$((ELAPSED + 10))
done
exit 1
- name: Setup API Token
id: token
run: |
set +e # Don't exit on error - we handle errors ourselves
echo "Testing v1 token authentication..."
V1_TOKEN="0123456789abcdef0123456789abcdef01234567"
# Test if v1 token works
RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Token $V1_TOKEN" http://localhost:8000/api/status/)
if [ "$RESPONSE" = "200" ]; then
echo "V1 token works - using legacy token"
echo "token=$V1_TOKEN" >> $GITHUB_OUTPUT
else
echo "V1 token failed (HTTP $RESPONSE) - creating v2 token for Netbox 4.5.0+"
# Create a v2 token using Netbox's Token model
DJANGO_OUTPUT=$(docker exec powernetbox-netbox-1 /opt/netbox/venv/bin/python /opt/netbox/netbox/manage.py shell -c "
import sys
from users.models import Token
from django.contrib.auth import get_user_model
try:
User = get_user_model()
user = User.objects.filter(username='admin').first()
if not user:
user = User.objects.create_superuser('admin', 'admin@example.com', 'admin')
# Delete existing tokens
Token.objects.filter(user=user).delete()
# Create token instance
token = Token(user=user)
# Generate the plaintext secret and set via property
secret = Token.generate()
token.token = secret
token.save()
# Output the full v2 token: nbt_{key}.{secret}
print(f'nbt_{token.key}.{secret}')
except Exception as e:
print(f'ERROR: {e}', file=sys.stderr)
" 2>&1)
# Extract the token line
TOKEN_OUTPUT=$(echo "$DJANGO_OUTPUT" | grep -E '^nbt_' || true)
if [ -n "$TOKEN_OUTPUT" ] && [[ "$TOKEN_OUTPUT" == nbt_* ]]; then
echo "Created v2 token: ${TOKEN_OUTPUT:0:20}..."
echo "::add-mask::$TOKEN_OUTPUT"
echo "token=$TOKEN_OUTPUT" >> $GITHUB_OUTPUT
else
echo "WARNING: Failed to create v2 token, using v1 fallback"
echo "token=$V1_TOKEN" >> $GITHUB_OUTPUT
fi
fi
- name: Install PowerShell dependencies
shell: pwsh
run: |
Set-PSRepository PSGallery -InstallationPolicy Trusted
Install-Module Pester -Force -Scope CurrentUser -MinimumVersion 5.0.0
- name: Build module
shell: pwsh
run: |
./deploy.ps1 -Environment dev -SkipVersion
Import-Module ./PowerNetbox/PowerNetbox.psd1 -Force
- name: Run integration tests
shell: pwsh
env:
NETBOX_HOST: ${{ env.NETBOX_HOST }}
NETBOX_TOKEN: ${{ steps.token.outputs.token }}
run: |
$config = New-PesterConfiguration
$config.Run.Path = './Tests/Integration.Tests.ps1'
$config.Run.Exit = $true
$config.Filter.Tag = @('Integration')
$config.TestResult.Enabled = $true
$config.TestResult.OutputPath = 'IntegrationResults.xml'
$config.TestResult.OutputFormat = 'NUnitXml'
$config.Output.Verbosity = 'Detailed'
Invoke-Pester -Configuration $config
- name: Upload integration results
uses: actions/upload-artifact@v4
if: always()
with:
name: integration-tests-${{ matrix.netbox_short }}
path: IntegrationResults.xml
retention-days: 30
- name: Cleanup
if: always()
run: docker compose -f docker-compose.ci.yml down -v --remove-orphans
# ============================================================
# Stage 7: Module Verification
# ============================================================
module-verification:
name: Module Verification
runs-on: ubuntu-latest
outputs:
command_count: ${{ steps.verify.outputs.command_count }}
module_version: ${{ steps.verify.outputs.module_version }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Build and verify module
id: verify
shell: pwsh
run: |
Write-Host "=== Building Module ===" -ForegroundColor Cyan
./deploy.ps1 -Environment prod -SkipVersion
Write-Host ""
Write-Host "=== Importing Module ===" -ForegroundColor Cyan
Import-Module ./PowerNetbox/PowerNetbox.psd1 -Force -ErrorAction Stop
$module = Get-Module PowerNetbox
Write-Host "Name: $($module.Name)"
Write-Host "Version: $($module.Version)"
$commands = Get-Command -Module PowerNetbox
$publicCommands = $commands | Where-Object { $_.Name -match '-' }
Write-Host ""
Write-Host "=== Command Statistics ===" -ForegroundColor Cyan
Write-Host "Total commands: $($commands.Count)"
Write-Host "Public commands: $($publicCommands.Count)"
$expectedMinimum = 400
if ($publicCommands.Count -lt $expectedMinimum) {
Write-Host "::error::Expected at least $expectedMinimum public commands, found $($publicCommands.Count)"
exit 1
}
Write-Host ""
Write-Host "=== Command Breakdown ===" -ForegroundColor Cyan
$breakdown = $publicCommands | Group-Object { ($_.Name -split '-')[0] } | Sort-Object Count -Descending
foreach ($group in $breakdown) {
Write-Host " $($group.Name): $($group.Count)"
}
# Set outputs
"command_count=$($publicCommands.Count)" >> $env:GITHUB_OUTPUT
"module_version=$($module.Version)" >> $env:GITHUB_OUTPUT
$publicCommands | Select-Object Name | ConvertTo-Json | Out-File "command-list.json"
- name: Upload command list
uses: actions/upload-artifact@v4
with:
name: module-verification
path: command-list.json
retention-days: 30
# ============================================================
# Final: Enhanced Release Readiness Report
# ============================================================
release-report:
name: Release Readiness Report
runs-on: ubuntu-latest
needs: [unit-tests, code-coverage, code-quality, documentation-validation, breaking-changes, integration-tests, module-verification]
if: always()
steps:
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Generate enhanced release report
shell: pwsh
run: |
$version = "${{ inputs.version }}"
$skipIntegration = "${{ inputs.skip_integration }}" -eq 'true'
$coverageThreshold = [int]"${{ inputs.coverage_threshold }}"
# Collect job results
$unitTests = "${{ needs.unit-tests.result }}"
$codeCoverage = "${{ needs.code-coverage.result }}"
$codeQuality = "${{ needs.code-quality.result }}"
$docsValidation = "${{ needs.documentation-validation.result }}"
$breakingChanges = "${{ needs.breaking-changes.result }}"
$integration = if ($skipIntegration) { "skipped" } else { "${{ needs.integration-tests.result }}" }
$moduleVerify = "${{ needs.module-verification.result }}"
# Get metrics from job outputs
$coveragePercent = "${{ needs.code-coverage.outputs.coverage_percent }}"
$coveredCommands = "${{ needs.code-coverage.outputs.covered_commands }}"
$totalCommands = "${{ needs.code-coverage.outputs.total_commands }}"
$missedFunctions = "${{ needs.code-coverage.outputs.missed_functions }}"
$totalFunctions = "${{ needs.documentation-validation.outputs.total_functions }}"
$documentedFunctions = "${{ needs.documentation-validation.outputs.documented_functions }}"
$docsPercent = "${{ needs.documentation-validation.outputs.documentation_percent }}"
$missingDocs = "${{ needs.documentation-validation.outputs.missing_docs }}"
$removedCommands = "${{ needs.breaking-changes.outputs.removed_commands }}"
$addedCommands = "${{ needs.breaking-changes.outputs.added_commands }}"
$removedCount = "${{ needs.breaking-changes.outputs.removed_count }}"
$addedCount = "${{ needs.breaking-changes.outputs.added_count }}"
$hasBreaking = "${{ needs.breaking-changes.outputs.has_breaking_changes }}"
$commandCount = "${{ needs.module-verification.outputs.command_count }}"
$moduleVersion = "${{ needs.module-verification.outputs.module_version }}"
# Determine overall status
$coverageOk = [double]$coveragePercent -ge $coverageThreshold
$allPassed = ($unitTests -eq 'success') -and
($codeCoverage -eq 'success') -and
($codeQuality -eq 'success') -and
($docsValidation -eq 'success') -and
($moduleVerify -eq 'success') -and
($skipIntegration -or $integration -eq 'success')
$overallStatus = if ($allPassed) { "READY" } else { "NOT READY" }
$statusEmoji = if ($allPassed) { "✅" } else { "❌" }
# Coverage status
$coverageStatus = if ([double]$coveragePercent -ge $coverageThreshold) { "✅" } else { "⚠️" }
$docsStatus = if ([double]$docsPercent -ge 80) { "✅" } elseif ([double]$docsPercent -ge 60) { "⚠️" } else { "❌" }
$breakingStatus = if ($hasBreaking -eq 'true') { "⚠️ BREAKING" } else { "✅ None" }
# Build report using StringBuilder to avoid YAML parsing issues with here-strings
$sb = [System.Text.StringBuilder]::new()
[void]$sb.AppendLine("# $statusEmoji Pre-Release Validation Report")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("**Version:** $version")
[void]$sb.AppendLine("**Module Version:** $moduleVersion")
[void]$sb.AppendLine("**Date:** $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss UTC')")
[void]$sb.AppendLine("**Status:** **$overallStatus**")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## Quality Metrics")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("| Metric | Value | Status |")
[void]$sb.AppendLine("|--------|-------|--------|")
[void]$sb.AppendLine("| **Code Coverage** | $coveragePercent% ($coveredCommands/$totalCommands commands) | $coverageStatus (threshold: $coverageThreshold%) |")
[void]$sb.AppendLine("| **Documentation** | $docsPercent% ($documentedFunctions/$totalFunctions functions) | $docsStatus |")
[void]$sb.AppendLine("| **Breaking Changes** | $removedCount removed, $addedCount added | $breakingStatus |")
[void]$sb.AppendLine("| **Public Commands** | $commandCount | OK |")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## Test Results")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("| Stage | Result | Details |")
[void]$sb.AppendLine("|-------|--------|---------|")
$utResult = if ($unitTests -eq 'success') { 'PASS' } else { 'FAIL' }
$ccResult = if ($codeCoverage -eq 'success') { 'PASS' } else { 'FAIL' }
$cqResult = if ($codeQuality -eq 'success') { 'PASS' } else { 'FAIL' }
$dvResult = if ($docsValidation -eq 'success') { 'PASS' } else { 'FAIL' }
$bcResult = if ($breakingChanges -eq 'success') { 'PASS' } else { 'FAIL' }
$itResult = if ($skipIntegration) { 'SKIPPED' } elseif ($integration -eq 'success') { 'PASS' } else { 'FAIL' }
$mvResult = if ($moduleVerify -eq 'success') { 'PASS' } else { 'FAIL' }
[void]$sb.AppendLine("| Unit Tests (4 platforms) | $utResult | Ubuntu, Windows, macOS + PS 5.1/7.x |")
[void]$sb.AppendLine("| Code Coverage | $ccResult | $coveragePercent% coverage |")
[void]$sb.AppendLine("| Code Quality (PSSA) | $cqResult | PSScriptAnalyzer |")
[void]$sb.AppendLine("| Documentation | $dvResult | $docsPercent% documented |")
[void]$sb.AppendLine("| Breaking Changes | $bcResult | $removedCount breaking, $addedCount new |")
[void]$sb.AppendLine("| Integration Tests | $itResult | Netbox 4.3, 4.4, 4.5 |")
[void]$sb.AppendLine("| Module Verification | $mvResult | Import, command count |")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## Platform Matrix")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("| Platform | PowerShell | Status |")
[void]$sb.AppendLine("|----------|------------|--------|")
$pStatus = if ($unitTests -eq 'success') { 'OK' } else { '?' }
[void]$sb.AppendLine("| Ubuntu | 7.x | $pStatus |")
[void]$sb.AppendLine("| Windows | 7.x | $pStatus |")
[void]$sb.AppendLine("| Windows | 5.1 | $pStatus |")
[void]$sb.AppendLine("| macOS | 7.x | $pStatus |")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## Netbox Compatibility")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("| Version | Status |")
[void]$sb.AppendLine("|---------|--------|")
$nbStatus = if ($skipIntegration) { 'SKIP' } elseif ($integration -eq 'success') { 'OK' } else { '?' }
[void]$sb.AppendLine("| 4.3.7 | $nbStatus |")
[void]$sb.AppendLine("| 4.4.10 | $nbStatus |")
[void]$sb.AppendLine("| 4.5.8 | $nbStatus |")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## Coverage Details")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("**Functions with 0% coverage (sample):** $missedFunctions")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("**Functions missing documentation (sample):** $missingDocs")
[void]$sb.AppendLine("")
if ($hasBreaking -eq 'true') {
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## WARNING: Breaking Changes Detected")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("**Removed commands:** $removedCommands")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("These commands exist in the PSGallery release but are missing from the current build.")
[void]$sb.AppendLine("Consider if this is intentional and document in release notes.")
[void]$sb.AppendLine("")
}
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## Release Checklist")
[void]$sb.AppendLine("")
$c1 = if ($unitTests -eq 'success') { 'x' } else { ' ' }
$c2 = if ($coverageOk) { 'x' } else { ' ' }
$c3 = if ($codeQuality -eq 'success') { 'x' } else { ' ' }
$c4 = if ($docsValidation -eq 'success') { 'x' } else { ' ' }
$c5 = if ($hasBreaking -ne 'true') { 'x' } else { ' ' }
$c6 = if ($skipIntegration -or $integration -eq 'success') { 'x' } else { ' ' }
$c7 = if ($moduleVerify -eq 'success') { 'x' } else { ' ' }
[void]$sb.AppendLine("- [$c1] All unit tests pass (4 platforms)")
[void]$sb.AppendLine("- [$c2] Code coverage >= $coverageThreshold%")
[void]$sb.AppendLine("- [$c3] No PSScriptAnalyzer errors")
[void]$sb.AppendLine("- [$c4] Documentation validated")
[void]$sb.AppendLine("- [$c5] No breaking changes (or documented)")
[void]$sb.AppendLine("- [$c6] Integration tests pass")
[void]$sb.AppendLine("- [$c7] Module loads correctly")
[void]$sb.AppendLine("- [ ] Version updated in PowerNetbox.psd1")
[void]$sb.AppendLine("- [ ] CHANGELOG updated")
[void]$sb.AppendLine("- [ ] PR approved")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## Next Steps")
[void]$sb.AppendLine("")
if ($allPassed) {
[void]$sb.AppendLine("1. Merge to main branch")
[void]$sb.AppendLine("2. Create release tag: v$version")
[void]$sb.AppendLine("3. GitHub Actions will publish to PSGallery")
} else {
[void]$sb.AppendLine("1. Review failed checks above")
[void]$sb.AppendLine("2. Fix issues and push updates")
[void]$sb.AppendLine("3. Re-run this validation workflow")