<# .SYNOPSIS 把 BakNRet 模块的多个源文件按加载器声明的顺序,拼成单个 .psm1 放进 dist\。 .DESCRIPTION 为什么需要它:拆分源码是为了好读、好 review、让每次改动落在小文件里;但 PowerShell 的 脚本模块在**发布形态**上更适合单个文件(加载更快、代码签名只需签一个文件、类与 using 语句的行为最可预测)。有了这个脚本,"拆开的源码"与"单文件的模块"都随时可得,而不是 只能二选一。 顺序从哪儿来:从 BakNRet\BakNRet.psm1 里读出来 —— 顺序只声明一次,这里不重复写一遍。 导出清单同理,直接照抄加载器尾部。 dist\ 已进 .gitignore:它是可重建的产物,不是源。 .PARAMETER WhatIf 只报告将要拼什么,不写文件。 .EXAMPLE .\tools\Build-BakNRetModule.ps1 -WhatIf .EXAMPLE .\tools\Build-BakNRetModule.ps1 #> [CmdletBinding(SupportsShouldProcess = $true)] param() $ErrorActionPreference = 'Stop' $projectRoot = Split-Path -Parent $PSScriptRoot $moduleRoot = Join-Path $projectRoot 'BakNRet' $loaderPath = Join-Path $moduleRoot 'BakNRet.psm1' if (-not (Test-Path -LiteralPath $loaderPath)) { throw "找不到加载器:$loaderPath" } $loaderLines = @(Get-Content -Encoding UTF8 -LiteralPath $loaderPath) # 顺序与导出清单都从加载器读 —— 这样"能不能合回去"不依赖任何人记得同时改两个地方 $sources = [System.Collections.Generic.List[string]]::new() foreach ($line in $loaderLines) { if ($line -match "^\. \(Join-Path \`$PSScriptRoot '([^']+)'\)$") { $sources.Add((Join-Path $moduleRoot ($Matches[1] -replace '/', '\'))) } } if ($sources.Count -eq 0) { throw '加载器里一个点源都没有 —— 顺序声明丢了?' } foreach ($source in $sources) { if (-not (Test-Path -LiteralPath $source)) { throw "加载器指向的文件不存在:$source" } } $exportStart = -1 for ($i = 0; $i -lt $loaderLines.Count; $i++) { if ($loaderLines[$i] -match '^Export-ModuleMember\b') { $exportStart = $i; break } } if ($exportStart -lt 0) { throw '加载器里找不到 Export-ModuleMember' } $exportBlock = @($loaderLines[$exportStart..($loaderLines.Count - 1)]) $distDir = Join-Path $projectRoot 'dist' $outputPath = Join-Path $distDir 'BakNRet.psm1' Write-Host '' Write-Host ("源文件 {0} 个" -f $sources.Count) Write-Host ("产物 {0}" -f $outputPath) if (-not $PSCmdlet.ShouldProcess($outputPath, ("拼成单文件({0} 个源文件)" -f $sources.Count))) { return } if (-not (Test-Path -LiteralPath $distDir)) { New-Item -ItemType Directory -Path $distDir -Force | Out-Null } $parts = foreach ($source in $sources) { (@(Get-Content -Encoding UTF8 -LiteralPath $source) -join "`n") } $text = (($parts -join "`n`n") + "`n`n" + ($exportBlock -join "`n") + "`n") [System.IO.File]::WriteAllText($outputPath, $text, (New-Object System.Text.UTF8Encoding($true))) # 产物必须能解析 —— 否则"合并"这件事只是把坏掉的东西藏起来 $errors = $null [void][System.Management.Automation.Language.Parser]::ParseFile($outputPath, [ref]$null, [ref]$errors) if ($errors -and $errors.Count) { throw ("拼出来的单文件解析失败({0} 个错误):{1}" -f $errors.Count, $errors[0].Message) } Write-Host '' Write-Host ("完成:{0} 行,{1:N1} KB" -f (Get-Content -LiteralPath $outputPath).Count, ((Get-Item $outputPath).Length / 1KB)) -ForegroundColor Green