[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Path, [string]$Output, [switch]$InPlace ) $ErrorActionPreference = 'Stop' $resolved = Resolve-Path -LiteralPath $Path -ErrorAction Stop if (-not (Test-Path -LiteralPath $resolved -PathType Leaf)) { throw "Укажите файл: $resolved" } if ($Output -and $InPlace) { throw 'Флаги -Output и -InPlace несовместимы' } if ($Output -and [IO.Path]::GetFullPath($Output) -eq $resolved.Path) { throw 'Выходной файл совпадает с входным, используйте -InPlace' } $lines = @(Get-Content -LiteralPath $resolved -Encoding UTF8) $inFence = $false $levels = New-Object System.Collections.Generic.List[int] foreach ($line in $lines) { if ($line -match '^\s*(```|~~~)') { $inFence = -not $inFence continue } if ($inFence) { continue } if ($line -match '^(#{1,6})\s+(.+)$') { $levels.Add($matches[1].Length) } } if ($levels.Count -eq 0) { throw 'Заголовки Markdown не найдены' } $minimum = ($levels | Measure-Object -Minimum).Minimum $shift = $minimum - 1 $previous = 0 $result = New-Object System.Collections.Generic.List[string] $inFence = $false $changed = 0 foreach ($line in $lines) { if ($line -match '^\s*(```|~~~)') { $inFence = -not $inFence $result.Add($line) continue } if (-not $inFence -and $line -match '^(#{1,6})\s+(.+)$') { $level = $matches[1].Length - $shift if ($level -lt 1) { $level = 1 } if ($level -gt $previous + 1) { $level = $previous + 1 } $previous = $level $prefix = ('#' * $level) -join '' $updated = $prefix + ' ' + $matches[2] if ($updated -ne $line) { $changed++ } $result.Add($updated) continue } $result.Add($line) } $text = ($result -join [Environment]::NewLine) + [Environment]::NewLine if ($InPlace) { $backup = $resolved.Path + '.bak' Copy-Item -LiteralPath $resolved.Path -Destination $backup -Force [IO.File]::WriteAllText($resolved.Path, $text, (New-Object System.Text.UTF8Encoding($false))) Write-Host "Файл обновлён, копия: $backup" } elseif ($Output) { $target = [IO.Path]::GetFullPath($Output) [IO.File]::WriteAllText($target, $text, (New-Object System.Text.UTF8Encoding($false))) Write-Host "Результат: $target" } else { Write-Output $text } Write-Host "Заголовков: $($levels.Count), изменено строк: $changed"