Private/Update-KadenDelimitedInstructionFile.ps1
|
function Update-KadenDelimitedInstructionFile { <# .SYNOPSIS Create or refresh one delimited instruction file. .DESCRIPTION Content supplies Header, Body, CreateWhenMissing, StartToken, EndToken, and Notice. A file that has neither marker keeps its text and receives the delimited block at the end. A broken marker pair is left unchanged and appended to Findings. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Initialize-KadenRepo and Update-KadenRepo already confirm ShouldProcess before this private write.')] [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$ChildRoot, [Parameter(Mandatory = $true)] [string]$RelativePath, [Parameter(Mandatory = $true)] $Content, [Parameter(Mandatory = $true)] $Findings ) $destination = Resolve-KadenContainedPath -Root $ChildRoot -RelativePath $RelativePath if (Test-Path -LiteralPath $destination) { $existingItem = Get-Item -LiteralPath $destination -Force $reparse = [System.IO.FileAttributes]::ReparsePoint if (($existingItem.Attributes -band $reparse) -ne 0) { $Findings.Add("The Kaden instruction path is not a regular file ('$RelativePath').") | Out-Null return } } $startToken = [string]$Content.StartToken $endToken = [string]$Content.EndToken $notice = [string]$Content.Notice $body = [string]$Content.Body $header = [string]$Content.Header $createWhenMissing = [bool]$Content.CreateWhenMissing $block = $startToken + "`n" + $notice + "`n" + $body + $endToken + "`n" $destination = Resolve-KadenContainedPath -Root $ChildRoot -RelativePath $RelativePath if (-not (Test-Path -LiteralPath $destination)) { if (-not $createWhenMissing) { return } Write-KadenTextAtomic -LiteralPath $destination -Text ($header + $block) return } $existing = [System.IO.File]::ReadAllText($destination) $startCount = Get-KadenMarkerCount -Text $existing -Token $startToken $endCount = Get-KadenMarkerCount -Text $existing -Token $endToken if ($startCount -eq 0 -and $endCount -eq 0) { $prefix = $existing if ($prefix.Length -gt 0 -and -not $prefix.EndsWith("`n")) { $prefix += "`n" } Write-KadenTextAtomic -LiteralPath $destination -Text ($prefix + $block) return } $startAt = $existing.IndexOf($startToken) $endAt = $existing.IndexOf($endToken) $ordered = ($startCount -eq 1 -and $endCount -eq 1 -and $startAt -ge 0 -and $endAt -gt $startAt) if (-not $ordered) { $Findings.Add("The Kaden instruction block is malformed in '$RelativePath'.") | Out-Null return } $prefix = $existing.Substring(0, $startAt + $startToken.Length) $suffix = $existing.Substring($endAt) $inner = "`n" + $notice + "`n" + $body $destination = Resolve-KadenContainedPath -Root $ChildRoot -RelativePath $RelativePath Write-KadenTextAtomic -LiteralPath $destination -Text ($prefix + $inner + $suffix) } |