Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,20 @@ jobs:
run: |
& pwsh -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE
exit $LASTEXITCODE

# The C# in Source/: ParallelKit.ps1 carries the same code, and it compiles
# with no warnings as C# 5 with the .NET Framework's compiler (Add-Type's on
# Windows PowerShell 5.1), and with the .NET SDK for the .NET pwsh runs on,
# with the analyzer rules the script lists.
csharp:
name: C#
runs-on: windows-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4

- name: Check and compile Source/*.cs
shell: powershell
run: |
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Build\Update-ParallelKitCSharp.ps1 -Check -Compile
exit $LASTEXITCODE
157 changes: 157 additions & 0 deletions Build/Update-ParallelKitCSharp.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
# Copies the kit's C# from Source/*.cs into ParallelKit.ps1, whose Add-Type
# blocks carry it, so the .ps1 stays one self-contained file. Edit the .cs
# files, then run this: never edit the C# inside ParallelKit.ps1.
#
# powershell -NoProfile -File .\Build\Update-ParallelKitCSharp.ps1 # update ParallelKit.ps1
# powershell -NoProfile -File .\Build\Update-ParallelKitCSharp.ps1 -Check # exit 1 if it isn't up to date
# powershell -NoProfile -File .\Build\Update-ParallelKitCSharp.ps1 -Compile # and compile the C#
#
# Each Source/<Type>.cs is the block guarded by <Type> in ParallelKit.ps1:
# if (-not ([System.Management.Automation.PSTypeName]'<Type>').Type) {
# Add-Type -TypeDefinition @'
# ...
# '@ -Language CSharp
# }
# Every block needs its file and every file its block. Nothing else in the
# .ps1 changes. Runs on Windows PowerShell 5.1 and PowerShell 7.
#
# -Compile builds each file on its own, as Add-Type does, twice: with the
# .NET Framework's csc.exe, the compiler Add-Type uses on 5.1 (C# 5), and
# with the .NET SDK at LangVersion 5 for the .NET that pwsh runs on, with the
# analyzer rules listed below. Warnings are errors in both. It needs pwsh and
# a .NET SDK that can target pwsh's .NET.
param(
[switch]$Check,
[switch]$Compile,
# The repository root, for testing on a copy.
[string]$Root = (Split-Path -Parent $PSScriptRoot)
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

$kitPath = Join-Path $Root 'ParallelKit.ps1'
$sourceDir = Join-Path $Root 'Source'
if (-not (Test-Path -LiteralPath $kitPath -PathType Leaf)) { throw "Update-ParallelKitCSharp: '$kitPath' doesn't exist. Pass -Root with the repository's folder." }
$sources = @(Get-ChildItem -LiteralPath $sourceDir -Filter '*.cs' -File -ErrorAction SilentlyContinue | Sort-Object Name)
if ($sources.Count -eq 0) { throw "Update-ParallelKitCSharp: no .cs files in '$sourceDir'." }

# Read and written as bytes decoded as UTF-8, keeping a byte-order mark only
# if the file had one, so a run that changes nothing writes nothing.
$kitBytes = [System.IO.File]::ReadAllBytes($kitPath)
$hasBom = $kitBytes.Length -ge 3 -and $kitBytes[0] -eq 0xEF -and $kitBytes[1] -eq 0xBB -and $kitBytes[2] -eq 0xBF
$utf8 = [System.Text.UTF8Encoding]::new($false, $true)
function Read-CSharpSourceText {
# Strict UTF-8, so a file saved in another encoding stops the run rather
# than being copied wrong.
param([byte[]]$Bytes, [int]$Skip, [string]$Name)
try { return $utf8.GetString($Bytes, $Skip, $Bytes.Length - $Skip) }
catch [System.Text.DecoderFallbackException] { throw ("Update-ParallelKitCSharp: " + $Name + " isn't valid UTF-8. Save it as UTF-8 and run this again.") }
}
$kitText = Read-CSharpSourceText -Bytes $kitBytes -Skip ([int]$hasBom * 3) -Name 'ParallelKit.ps1'
$newline = if ($kitText.Contains("`r`n")) { "`r`n" } else { "`n" }

$blockCount = [regex]::Matches($kitText, "(?m)^ Add-Type -TypeDefinition @'\r?$").Count
if ($blockCount -ne $sources.Count) {
throw ("Update-ParallelKitCSharp: ParallelKit.ps1 has " + $blockCount + " Add-Type block(s) and Source has " + $sources.Count + " .cs file(s) (" + (($sources | ForEach-Object Name) -join ', ') + "). Each block needs a file named after the type that guards it, and each file a block.")
}

$updated = $kitText
$stale = [System.Collections.Generic.List[string]]::new()
foreach ($source in $sources) {
$type = [System.IO.Path]::GetFileNameWithoutExtension($source.Name)
$pattern = "(?s)(if \(-not \(\[System\.Management\.Automation\.PSTypeName\]'" + [regex]::Escape($type) + "'\)\.Type\) \{\r?\n Add-Type -TypeDefinition @'\r?\n)(.*?)(\r?\n'@ -Language CSharp\r?\n\})"
$found = [regex]::Matches($updated, $pattern)
if ($found.Count -ne 1) { throw ("Update-ParallelKitCSharp: expected one Add-Type block guarded by '" + $type + "' in ParallelKit.ps1 (for " + $source.Name + "), found " + $found.Count + ". The guard and the Add-Type line must keep the form shown at the top of this script.") }
$code = Read-CSharpSourceText -Bytes ([System.IO.File]::ReadAllBytes($source.FullName)) -Skip 0 -Name $source.Name
if ($code.Length -gt 0 -and $code[0] -eq [char]0xFEFF) { $code = $code.Substring(1) }
$code = ($code -replace "\r\n", "`n") -replace "\n\z", ''
# A line starting with '@ would end the here-string early.
if ($code -match "(?m)^'@") { throw ("Update-ParallelKitCSharp: " + $source.Name + " has a line starting with '@, which would end ParallelKit.ps1's here-string there. Indent it or rewrite it.") }
$code = $code.Replace("`n", $newline)
$match = $found[0]
if ($match.Groups[2].Value -cne $code) { $stale.Add($source.Name) }
$updated = $updated.Substring(0, $match.Groups[2].Index) + $code + $updated.Substring($match.Groups[2].Index + $match.Groups[2].Length)
}

if ($Check) {
if ($stale.Count -gt 0) {
Write-Host ("ParallelKit.ps1 doesn't match " + ($stale -join ', ') + ". Run Build/Update-ParallelKitCSharp.ps1 and commit both.") -ForegroundColor Red
exit 1
}
Write-Host ("ParallelKit.ps1 matches Source/ (" + $sources.Count + " files).")
} elseif ($stale.Count -gt 0) {
$bom = if ($hasBom) { [byte[]](0xEF, 0xBB, 0xBF) } else { [byte[]]@() }
[System.IO.File]::WriteAllBytes($kitPath, [byte[]]($bom + $utf8.GetBytes($updated)))
Write-Host ("Updated ParallelKit.ps1 from " + ($stale -join ', ') + ".")
} else {
Write-Host "ParallelKit.ps1 already matches Source/."
}

if (-not $Compile) { exit 0 }

$work = Join-Path ([System.IO.Path]::GetTempPath()) ("pk-csharp-" + [System.Guid]::NewGuid().ToString('N'))
$null = New-Item -ItemType Directory -Path $work
$failed = [System.Collections.Generic.List[string]]::new()
try {
# The .NET Framework 4.x compiler, as Add-Type on 5.1 uses it.
$frameworkDir = if ([Environment]::Is64BitOperatingSystem) { 'Framework64' } else { 'Framework' }
$csc = Join-Path $env:SystemRoot ("Microsoft.NET\" + $frameworkDir + "\v4.0.30319\csc.exe")
if (-not (Test-Path -LiteralPath $csc -PathType Leaf)) { throw "Update-ParallelKitCSharp: the .NET Framework compiler isn't at '$csc'. -Compile needs Windows with .NET Framework 4.x." }
foreach ($source in $sources) {
$out = & $csc /nologo /target:library /langversion:5 /warn:4 /warnaserror+ ("/out:" + (Join-Path $work ($source.BaseName + '.framework.dll'))) $source.FullName 2>&1
if ($LASTEXITCODE -ne 0) { $failed.Add('csc.exe ' + $source.Name); $out | ForEach-Object { Write-Host (" " + $_) } }
else { Write-Host ("csc.exe (C# 5): " + $source.Name + " compiles with no warnings.") }
}

# The .NET SDK, for the .NET that pwsh runs on.
$pwsh = Get-Command pwsh -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -eq $pwsh) { throw "Update-ParallelKitCSharp: -Compile needs pwsh (PowerShell 7) on PATH, to target the .NET it runs on." }
$dotnet = Get-Command dotnet -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -eq $dotnet) { throw "Update-ParallelKitCSharp: -Compile needs the .NET SDK (dotnet) on PATH." }
$runtime = (& $pwsh.Source -NoProfile -Command '[Environment]::Version.ToString(2)').Trim()
$targetFramework = 'net' + $runtime
# Analyzer rules checked on top of the compiler's own warnings: ones about
# real faults, all clean today. Left out on purpose: style rules, and ones
# this code breaks deliberately (catch-all handlers that report the
# failure; DllImport of kernel32, a KnownDLL; handles a catch block
# releases, which the dispose rule can't follow).
$rules = @('CA1069', 'CA2002', 'CA2011', 'CA2013', 'CA2101', 'CA2200', 'CA2201', 'CA2208', 'CA2213', 'CA2216', 'CA2219', 'CA2241')
$config = @('is_global = true') + @($rules | ForEach-Object { 'dotnet_diagnostic.' + $_ + '.severity = warning' })
foreach ($source in $sources) {
$project = Join-Path $work $source.BaseName
$null = New-Item -ItemType Directory -Path $project
[System.IO.File]::WriteAllLines((Join-Path $project 'rules.globalconfig'), [string[]]$config)
[System.IO.File]::WriteAllText((Join-Path $project 'check.csproj'), (@'
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>FRAMEWORK</TargetFramework>
<LangVersion>5</LangVersion>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisMode>None</AnalysisMode>
</PropertyGroup>
<ItemGroup>
<Compile Include="SOURCE" />
<GlobalAnalyzerConfigFiles Include="rules.globalconfig" />
</ItemGroup>
</Project>
'@).Replace('FRAMEWORK', $targetFramework).Replace('SOURCE', $source.Name))
# A copy next to the project, included by its bare name: MSBuild reads
# characters such as % ; * $ in an item's path as its own syntax.
Copy-Item -LiteralPath $source.FullName -Destination $project
$out = & $dotnet.Source build (Join-Path $project 'check.csproj') -nologo -v:q --disable-build-servers 2>&1
if ($LASTEXITCODE -ne 0) { $failed.Add('dotnet ' + $source.Name); $out | ForEach-Object { Write-Host (" " + $_) } }
else { Write-Host ("dotnet (" + $targetFramework + ", LangVersion 5): " + $source.Name + " compiles with no warnings.") }
}
} finally {
Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue
}
if ($failed.Count -gt 0) {
Write-Host ("Didn't compile cleanly: " + ($failed -join ', ') + ".") -ForegroundColor Red
exit 1
}
exit 0
49 changes: 49 additions & 0 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -6077,6 +6077,55 @@ Test-Assert ($bmOtherBuild.Results[0].ExitCode -eq 0 -and $bmStaleOut -like '*re
Write-Host ""
}

# ==============================================================================
if (Test-HarnessSection 'BN' "the C# in Source/ and in ParallelKit.ps1 match") {
# The C# is edited in Source/*.cs, and Build/Update-ParallelKitCSharp.ps1
# copies it into ParallelKit.ps1's Add-Type blocks. Its checks are tested on a
# copy of the kit and its sources in %TEMP%. Compiling (-Compile) needs the
# .NET SDK, so it's checked by CI's C# job, not here.
$bnScript = Join-Path $PSScriptRoot 'Build\Update-ParallelKitCSharp.ps1'
$null = & $bnScript -Check 6>$null
Test-Assert ($LASTEXITCODE -eq 0) "ParallelKit.ps1's C# matches Source/*.cs (Build/Update-ParallelKitCSharp.ps1 -Check)"

$bnDir = Join-Path $env:TEMP ("pk-harness-bn-" + $PID)
try {
$null = New-Item -ItemType Directory -Force -Path (Join-Path $bnDir 'Source')
Copy-Item -LiteralPath $kitPs1 -Destination $bnDir
Copy-Item -Path (Join-Path $PSScriptRoot 'Source\*.cs') -Destination (Join-Path $bnDir 'Source')
$bnKit = Join-Path $bnDir 'ParallelKit.ps1'
$bnCs = Join-Path $bnDir 'Source\PkConsoleQuickEdit.cs'
$bnKitText = [System.IO.File]::ReadAllText($bnKit)
$bnCsText = [System.IO.File]::ReadAllText($bnCs)

# An edit to one .cs file: -Check fails, the update copies that one line
# into its own block and nothing else, and -Check passes again.
[System.IO.File]::WriteAllText($bnCs, $bnCsText.Replace('using System;', 'using System; // pk-harness-bn'))
$null = & $bnScript -Root $bnDir -Check 6>$null
$bnStale = $LASTEXITCODE
$null = & $bnScript -Root $bnDir 6>$null
$bnUpdated = [System.IO.File]::ReadAllText($bnKit)
$null = & $bnScript -Root $bnDir -Check 6>$null
$bnFresh = $LASTEXITCODE
$bnAt = $bnKitText.IndexOf('using System;', $bnKitText.IndexOf("'PkConsoleQuickEdit'"))
$bnExpected = $bnKitText.Substring(0, $bnAt) + 'using System; // pk-harness-bn' + $bnKitText.Substring($bnAt + 'using System;'.Length)
Test-Assert ($bnStale -eq 1 -and $bnFresh -eq 0 -and $bnUpdated -ceq $bnExpected) ("an edited .cs file: -Check fails (exit " + $bnStale + "), the update changes only that line in its block (" + ($bnUpdated -ceq $bnExpected) + "), then -Check passes (exit " + $bnFresh + ")")

# Refused, with a message: a line starting with '@, which would end the
# here-string, and a block left without its file.
[System.IO.File]::WriteAllText($bnCs, $bnCsText + "'@`r`n")
$bnTerminator = ''
try { $null = & $bnScript -Root $bnDir 6>$null } catch { $bnTerminator = [string]$_ }
[System.IO.File]::WriteAllText($bnCs, $bnCsText)
Rename-Item -LiteralPath $bnCs -NewName 'PkConsoleQuickEdit.txt'
$bnMissing = ''
try { $null = & $bnScript -Root $bnDir 6>$null } catch { $bnMissing = [string]$_ }
Test-Assert ($bnTerminator -like "*line starting with '@*" -and $bnMissing -like '*has 3 Add-Type block(s) and Source has 2 .cs file(s)*' -and [System.IO.File]::ReadAllText($bnKit) -ceq $bnUpdated) ("the update refuses a line starting with '@ and a block without its file, and leaves ParallelKit.ps1 alone (" + $bnTerminator + " / " + $bnMissing + ")")
} finally {
Remove-Item -LiteralPath $bnDir -Recurse -Force -ErrorAction SilentlyContinue
}
Write-Host ""
}

Set-PkMessageHandler -Handler $null
Reset-PkAbortState
if ($null -ne $moduleDir) {
Expand Down
2 changes: 2 additions & 0 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock {
# ==============================================================================
# Native types (guarded so the kit can be loaded more than once)
# ==============================================================================
# The C# below is copied from Source/<Type>.cs by
# Build/Update-ParallelKitCSharp.ps1: edit it there, then run that script.

if (-not ([System.Management.Automation.PSTypeName]'PkConsoleCtrl').Type) {
Add-Type -TypeDefinition @'
Expand Down
Loading
Loading