#!/usr/bin/env pwsh <# .SYNOPSIS Fixes misplaced 'using StellaOps.TestKit;' statements in test files. .DESCRIPTION The validate-test-traits.py --fix script has a bug that inserts 'using StellaOps.TestKit;' after 'using var' statements inside methods, causing compilation errors. This script: 1. Finds all affected .cs files 2. Removes the misplaced 'using StellaOps.TestKit;' lines 3. Ensures 'using StellaOps.TestKit;' exists at the top of the file #> param( [string]$Path = "src", [switch]$DryRun ) $ErrorActionPreference = "Stop" # Pattern to find misplaced using statements (after 'using var' in method body) $brokenPattern = "(?m)^(\s*using var .+;\s*\r?\n)(using StellaOps\.TestKit;\s*\r?\n)" # Counter for fixed files $fixedCount = 0 $checkedCount = 0 # Get all .cs test files $files = Get-ChildItem -Path $Path -Recurse -Include "*.cs" | Where-Object { $_.FullName -match "Tests?" } foreach ($file in $files) { $checkedCount++ $content = Get-Content -Path $file.FullName -Raw -Encoding UTF8 # Check if file has the broken pattern if ($content -match $brokenPattern) { Write-Host "Fixing: $($file.FullName)" -ForegroundColor Yellow # Remove all misplaced 'using StellaOps.TestKit;' lines $fixed = $content -replace $brokenPattern, '$1' # Check if 'using StellaOps.TestKit;' exists at the top of the file (in the using block) $hasTopUsing = $fixed -match "(?m)^using StellaOps\.TestKit;\s*$" if (-not $hasTopUsing) { # Find the last 'using' statement at the top of the file and add after it $fixed = $fixed -replace "(?m)(^using [^;]+;\s*\r?\n)(?!using)", "`$1using StellaOps.TestKit;`r`n" } if (-not $DryRun) { # Preserve BOM if original file had one $encoding = [System.Text.UTF8Encoding]::new($true) [System.IO.File]::WriteAllText($file.FullName, $fixed, $encoding) } $fixedCount++ } } Write-Host "`nChecked: $checkedCount files" -ForegroundColor Cyan Write-Host "Fixed: $fixedCount files" -ForegroundColor Green if ($DryRun) { Write-Host "`n(Dry run - no files were modified)" -ForegroundColor Magenta }