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
13 changes: 13 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ jobs:
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1
exit $LASTEXITCODE

# The same in harness-pwsh below: keep the two in step.
- name: Run the loading sections on the module
shell: powershell
run: |
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE
exit $LASTEXITCODE

# PowerShell 7 on Windows is supported alongside 5.1, so this is a required
# check too.
harness-pwsh:
Expand All @@ -44,3 +51,9 @@ jobs:
run: |
& pwsh -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1
exit $LASTEXITCODE

- name: Run the loading sections on the module under pwsh
shell: pwsh
run: |
& pwsh -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE
exit $LASTEXITCODE
170 changes: 170 additions & 0 deletions Build/New-ParallelKitModule.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
# Builds the PowerShell module from ParallelKit.ps1: ParallelKit.psm1 and its
# manifest, ParallelKit.psd1.
#
# .\Build\New-ParallelKitModule.ps1 -OutputDirectory C:\Modules\ParallelKit
#
# The folder has to be called ParallelKit, or be a version folder inside one
# (ParallelKit\4.0), for Import-Module to find it by name.
#
# The .psm1 is the .ps1 without the wrapper that loads it as an in-memory
# module: the Get-Module | Remove-Module line, and the New-Module wrapper's first
# and last lines. Everything is checked before anything is written, so a .ps1
# that doesn't look as expected stops this script and leaves the output folder
# alone. The same .ps1 always gives the same bytes, on 5.1 and 7, with LF or CRLF
# line endings. Exit code 0 = written, 1 = refused.
param(
# Default: the ParallelKit.ps1 one folder up.
[string]$SourcePath = '',
[Parameter(Mandatory)]
[string]$OutputDirectory
)

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest

# The module's identity on the PowerShell Gallery: never changes.
$moduleGuid = '1a05c60a-cafb-4e52-98e8-dd52affd2d61'
$removeLine = 'Get-Module -Name ParallelKit | Remove-Module'
$openLine = 'New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock {'
$closeLine = '} | Import-Module -Global'

function Stop-PkBuild {
param([string]$Why)
throw ("New-ParallelKitModule: '" + $SourcePath + "' doesn't look as expected, so nothing was written: " + $Why)
}

function Get-PkBuildLineIndex {
# Where the one line reading exactly $Text is; stops the build unless there's exactly one.
param([string[]]$Lines, [string]$Text)
$found = @(for ($i = 0; $i -lt $Lines.Count; $i++) { if ($Lines[$i] -ceq $Text) { $i } })
if ($found.Count -ne 1) { Stop-PkBuild ("expected exactly one line reading '" + $Text + "', found " + $found.Count + ". If the kit's loading changed, update this script to match.") }
return $found[0]
}

function Get-PkBuildAst {
param([string]$Text, [string]$What)
$tokens = $null; $parseErrors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$tokens, [ref]$parseErrors)
if (@($parseErrors).Count -gt 0) { Stop-PkBuild ($What + " has a syntax error at line " + $parseErrors[0].Extent.StartLineNumber + ": " + $parseErrors[0].Message) }
return $ast
}

function Get-PkBuildCommandCall {
param($Ast, [string[]]$Name)
return ,@($Ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.CommandAst] }, $true) | Where-Object { $Name -contains $_.GetCommandName() })
}

function Get-PkBuildFunctionName {
# The names of the functions defined directly in a list of statements.
param($Statements)
return @($Statements | Where-Object { $_ -is [System.Management.Automation.Language.FunctionDefinitionAst] } | ForEach-Object { $_.Name })
}

try {
# Not a parameter default: there, with -File on 5.1, $PSScriptRoot is empty.
if ($SourcePath -eq '') { $SourcePath = Join-Path (Split-Path -Parent $PSScriptRoot) 'ParallelKit.ps1' }
if (-not (Test-Path -LiteralPath $SourcePath -PathType Leaf)) { throw ("New-ParallelKitModule: there's no file at '" + $SourcePath + "'. Pass -SourcePath the path of ParallelKit.ps1.") }
$SourcePath = (Get-Item -LiteralPath $SourcePath).FullName
$OutputDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory)

# The .ps1 is ASCII, which 5.1 and 7 read alike without a BOM.
$bytes = [System.IO.File]::ReadAllBytes($SourcePath)
for ($i = 0; $i -lt $bytes.Length; $i++) {
if ($bytes[$i] -gt 127) { Stop-PkBuild ("byte " + $i + " isn't ASCII. 5.1 and 7 would read the file differently.") }
}
$source = [System.Text.Encoding]::ASCII.GetString($bytes).Replace("`r`n", "`n")
if ($source.Contains("`r")) { Stop-PkBuild "it has a carriage return on its own, not part of a CRLF." }
$lines = $source.TrimEnd("`n").Split("`n")
$sourceAst = Get-PkBuildAst -Text $source -What 'the file'

# The three lines, in their places.
$removeAt = Get-PkBuildLineIndex -Lines $lines -Text $removeLine
$openAt = Get-PkBuildLineIndex -Lines $lines -Text $openLine
$closeAt = Get-PkBuildLineIndex -Lines $lines -Text $closeLine
if ($openAt -ne $removeAt + 1) { Stop-PkBuild ("the New-Module line (" + ($openAt + 1) + ") isn't right after the Remove-Module line (" + ($removeAt + 1) + ").") }
if ($closeAt -ne $lines.Count - 1) { Stop-PkBuild ("there's more after the closing '" + $closeLine + "' (line " + ($closeAt + 1) + "), which would end up in the module's own scope.") }

# At the top level: the language mode check, then those two statements.
$top = @($sourceAst.EndBlock.Statements)
if ($null -ne $sourceAst.ParamBlock -or $null -ne $sourceAst.BeginBlock -or $null -ne $sourceAst.ProcessBlock -or $top.Count -ne 3) { Stop-PkBuild ("expected three top-level statements (the language mode check, Remove-Module, New-Module), found " + $top.Count + ".") }
if ($top[0] -isnot [System.Management.Automation.Language.IfStatementAst] -or $top[0].Extent.Text -notlike '*LanguageMode*') { Stop-PkBuild "the first statement isn't the language mode check." }
if ($top[1].Extent.StartLineNumber -ne $removeAt + 1 -or $top[2].Extent.StartLineNumber -ne $openAt + 1 -or $top[2].Extent.EndLineNumber -ne $closeAt + 1) { Stop-PkBuild "the wrapper's lines don't start and end the statements they should." }
$wrapped = @($top[2].PipelineElements[0].CommandElements)[-1]
if ($wrapped -isnot [System.Management.Automation.Language.ScriptBlockExpressionAst]) { Stop-PkBuild "New-Module's last argument isn't a scriptblock." }

# The module: every line but those three.
$kept = @(for ($i = 0; $i -lt $lines.Count; $i++) { if ($i -ne $removeAt -and $i -ne $openAt -and $i -ne $closeAt) { $lines[$i] } })
$module = (($kept -join "`n").TrimEnd("`n")) + "`n"
$moduleAst = Get-PkBuildAst -Text $module -What 'the module made from it'
$left = Get-PkBuildCommandCall -Ast $moduleAst -Name @('New-Module', 'Import-Module', 'Remove-Module')
if ($left.Count -gt 0) { Stop-PkBuild ("the module would still call " + $left[0].GetCommandName() + " (line " + $left[0].Extent.StartLineNumber + " of the module: '" + $left[0].Extent.Text + "').") }

# The same functions, now at the top level.
$moduleFns = Get-PkBuildFunctionName -Statements $moduleAst.EndBlock.Statements
$sourceFns = Get-PkBuildFunctionName -Statements $wrapped.ScriptBlock.EndBlock.Statements
if (@($moduleFns).Count -eq 0 -or ($moduleFns -join ',') -cne ($sourceFns -join ',')) { Stop-PkBuild ("the module has " + @($moduleFns).Count + " top-level functions and the kit " + @($sourceFns).Count + "; they should be the same list.") }
$doubled = @($moduleFns | Group-Object | Where-Object { $_.Count -gt 1 } | ForEach-Object { $_.Name })
if ($doubled.Count -gt 0) { Stop-PkBuild ("a function is defined twice: " + ($doubled -join ', ') + ".") }

# The public list: plain names, each one a function.
$exports = Get-PkBuildCommandCall -Ast $moduleAst -Name @('Export-ModuleMember')
if ($exports.Count -ne 1) { Stop-PkBuild ("expected one Export-ModuleMember, found " + $exports.Count + ".") }
if (@($moduleAst.EndBlock.Statements)[-1].Extent.StartOffset -ne $exports[0].Extent.StartOffset) { Stop-PkBuild "Export-ModuleMember isn't the module's last statement." }
$elements = @($exports[0].CommandElements)
if ($elements.Count -ne 3 -or $elements[1] -isnot [System.Management.Automation.Language.CommandParameterAst] -or $elements[1].ParameterName -ne 'Function') { Stop-PkBuild "Export-ModuleMember isn't of the form 'Export-ModuleMember -Function @(...)'." }
$public = @($elements[2].FindAll({ param($n) $n -is [System.Management.Automation.Language.ExpressionAst] -and $n -isnot [System.Management.Automation.Language.ArrayExpressionAst] -and $n -isnot [System.Management.Automation.Language.ArrayLiteralAst] }, $true) | ForEach-Object {
if ($_ -isnot [System.Management.Automation.Language.StringConstantExpressionAst]) { Stop-PkBuild ("Export-ModuleMember's list has something that isn't a plain name: " + $_.Extent.Text) }
$_.Value
})
if ($public.Count -eq 0) { Stop-PkBuild "Export-ModuleMember's list is empty." }
foreach ($name in $public) {
if ($moduleFns -cnotcontains $name) { Stop-PkBuild ("Export-ModuleMember lists '" + $name + "', which isn't a function in the kit.") }
}
if (@($public | Select-Object -Unique).Count -ne $public.Count) { Stop-PkBuild "Export-ModuleMember's list names a function twice." }

# The version: the header and Initialize-ParallelKit agree.
$header = [regex]::Matches($source, '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b')
$inCode = [regex]::Matches($source, "(?m)^ \`$version = \[version\]'(\d+\.\d+(?:\.\d+)?)'`$")
if ($header.Count -ne 1 -or $inCode.Count -ne 1) { Stop-PkBuild ("expected one '# Version X.Y' line and one `$version = [version]'X.Y' line, found " + $header.Count + " and " + $inCode.Count + ".") }
$version = $header[0].Groups[1].Value
if ($version -cne $inCode[0].Groups[1].Value) { Stop-PkBuild ("the header says version " + $version + " and Initialize-ParallelKit " + $inCode[0].Groups[1].Value + ".") }

# Written out rather than made by New-ModuleManifest, which puts the date
# and the user's name in the file.
$fnLines = (@($public | ForEach-Object { " '" + $_ + "'" }) -join ",`n")
$manifest = @'
@{
RootModule = 'ParallelKit.psm1'
ModuleVersion = '__VERSION__'
GUID = '__MODULEGUID__'
Author = 'HalRiveria'
Copyright = '(c) 2026 HalRiveria. MIT License.'
Description = 'Parallel runspace jobs, bounded external-process dispatch, and graceful Ctrl+C/window-close handling for Windows PowerShell 5.1 and PowerShell 7, with a Job Object so child processes die with the script. Windows only.'
PowerShellVersion = '5.1'
CompatiblePSEditions = @('Desktop', 'Core')
FunctionsToExport = @(
__FUNCTIONS__
)
CmdletsToExport = @()
VariablesToExport = @()
AliasesToExport = @()
PrivateData = @{
PSData = @{
Tags = @('Windows', 'Parallel', 'Runspace', 'Process', 'Concurrency', 'PSEdition_Desktop', 'PSEdition_Core')
LicenseUri = 'https://github.com/HalRiveria/PowerShell-ParallelKit/blob/main/LICENSE'
ProjectUri = 'https://github.com/HalRiveria/PowerShell-ParallelKit'
}
}
}
'@
$manifest = $manifest.Replace("`r`n", "`n").Replace('__VERSION__', $version).Replace('__MODULEGUID__', $moduleGuid).Replace('__FUNCTIONS__', $fnLines) + "`n"
$null = Get-PkBuildAst -Text $manifest -What 'the manifest made from it'

$null = New-Item -ItemType Directory -Force -Path $OutputDirectory
[System.IO.File]::WriteAllBytes((Join-Path $OutputDirectory 'ParallelKit.psm1'), [System.Text.Encoding]::ASCII.GetBytes($module.Replace("`n", "`r`n")))
[System.IO.File]::WriteAllBytes((Join-Path $OutputDirectory 'ParallelKit.psd1'), [System.Text.Encoding]::ASCII.GetBytes($manifest.Replace("`n", "`r`n")))
Write-Output ("Wrote ParallelKit " + $version + " (" + @($moduleFns).Count + " functions, " + $public.Count + " public) to " + $OutputDirectory)
} catch {
[Console]::Error.WriteLine($_.Exception.Message)
exit 1
}
Loading
Loading