param( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string[]] $ShaFiles, [string] $RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path, [switch] $WhatIf ) Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" function Resolve-HashTargetPath { param( [Parameter(Mandatory = $true)] [string] $ShaFileDirectory, [Parameter(Mandatory = $true)] [string] $PathText ) $candidateRepoRoot = Join-Path $RepoRoot $PathText if (Test-Path -LiteralPath $candidateRepoRoot -PathType Leaf) { return (Resolve-Path -LiteralPath $candidateRepoRoot).Path } $candidateLocal = Join-Path $ShaFileDirectory $PathText if (Test-Path -LiteralPath $candidateLocal -PathType Leaf) { return (Resolve-Path -LiteralPath $candidateLocal).Path } throw "SHA256SUMS entry not found: '$PathText' (checked repo root and '$ShaFileDirectory')" } function Write-Utf8NoBomLf { param( [Parameter(Mandatory = $true)] [string] $Path, [Parameter(Mandatory = $true)] [string] $Content ) $utf8NoBom = New-Object System.Text.UTF8Encoding($false) $bytes = $utf8NoBom.GetBytes($Content) [System.IO.File]::WriteAllBytes($Path, $bytes) } foreach ($shaFile in $ShaFiles) { $shaFilePath = (Resolve-Path -LiteralPath $shaFile).Path $shaFileDir = Split-Path -Parent $shaFilePath $inputLines = Get-Content -LiteralPath $shaFilePath $outputLines = New-Object System.Collections.Generic.List[string] foreach ($line in $inputLines) { $trimmed = $line.Trim() if ($trimmed.Length -eq 0 -or $trimmed.StartsWith("#")) { $outputLines.Add($line) continue } $pathText = $null $format = $null $separator = " " if ($trimmed -match "^([0-9a-fA-F]{64})(\s+)(.+)$") { $format = "hash-first" $separator = $Matches[2] $pathText = $Matches[3].Trim() } elseif ($trimmed -match "^(.+?)(\s+)([0-9a-fA-F]{64})$") { $format = "path-first" $separator = $Matches[2] $pathText = $Matches[1].Trim() } else { throw "Unrecognized SHA256SUMS line format in '$shaFilePath': $line" } $targetPath = Resolve-HashTargetPath -ShaFileDirectory $shaFileDir -PathText $pathText $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $targetPath).Hash.ToLowerInvariant() if ($format -eq "hash-first") { $outputLines.Add("$hash$separator$pathText") } else { $outputLines.Add("$pathText$separator$hash") } } $content = ($outputLines -join "`n") + "`n" if ($WhatIf) { Write-Output "[whatif] Would update $shaFilePath" continue } Write-Utf8NoBomLf -Path $shaFilePath -Content $content Write-Output "Updated $shaFilePath" }