Private/ConvertFrom-FrontMatterYaml.ps1
|
function ConvertFrom-FrontMatterYaml { <# .SYNOPSIS Reads the front matter of a post file that is written in YAML. .DESCRIPTION PowerShell has no YAML reader, and front matter needs little of YAML. This reads the part that front matter is written in: title: My post featured: true tags: [News, "Release notes"] authors: - jane@example.org custom_excerpt: > A longer text, written over several lines. A value is text, true or false, a list, or a block of text after | (lines are kept) or > (lines are joined). Text can be written between single or double quotes, which it needs when it starts with a character that means something in YAML, contains a # after a space, or has to stay text where true would become a boolean. A list is written between brackets or as lines that start with a dash. A # starts a comment, on a line of its own or after a value and a space. A value that is left empty is empty text. A number and a date stay text: the fields of a post that take them convert the text themselves. What front matter does not need is not read and stops with an error that names the line: a value inside a value, as a tag with a description of its own would be, and anchors and tags of YAML. Write such front matter as JSON, which Read-GhostPostFile reads as well. .EXAMPLE ConvertFrom-FrontMatterYaml -Yaml "title: My post`ntags: [News, Releases]" Returns an ordered dictionary with the keys title and tags, the second one holding a list of two. #> [CmdletBinding()] [OutputType([System.Collections.Specialized.OrderedDictionary])] param( # The YAML between the two lines of three dashes. [Parameter(Mandatory)] [AllowEmptyString()] [string] $Yaml ) # Reads one value that is written on a single line: quoted text, true, false, nothing, or plain text. $readScalar = { param([string] $Text, [int] $Number) $value = $Text.Trim() if ($value.StartsWith('"')) { $match = [regex]::Match($value, '^"(?<text>(?:[^"\\]|\\.)*)"\s*(?:#.*)?$') if (-not $match.Success) { throw "Line $Number of the front matter has text in double quotes that is not closed: $value" } $escapes = @{ 'n' = "`n"; 't' = "`t"; 'r' = "`r"; '"' = '"'; '\' = '\'; '/' = '/'; '0' = "`0" } return [regex]::Replace($match.Groups['text'].Value, '\\(.)', { param($escape) $character = $escape.Groups[1].Value if ($escapes.ContainsKey($character)) { $escapes[$character] } else { $character } }) } if ($value.StartsWith("'")) { $match = [regex]::Match($value, "^'(?<text>(?:[^']|'')*)'\s*(?:#.*)?$") if (-not $match.Success) { throw "Line $Number of the front matter has text in single quotes that is not closed: $value" } return $match.Groups['text'].Value.Replace("''", "'") } # A comment after plain text starts with a space and a #. $value = ($value -replace '\s+#.*$').Trim() if ($value -match '^[&*!|>%@`]') { throw "Line $Number of the front matter uses YAML that is not supported: $value. Put the text in quotes." } if ($value -ceq 'true' -or $value -ceq 'True' -or $value -ceq 'TRUE') { return $true } if ($value -ceq 'false' -or $value -ceq 'False' -or $value -ceq 'FALSE') { return $false } if ($value -eq '' -or $value -ceq 'null' -or $value -ceq '~') { return '' } $value } # Reads a list that is written between brackets: [a, "b, c", d]. $readFlowList = { param([string] $Text, [int] $Number) $match = [regex]::Match($Text.Trim(), '^\[(?<items>.*)\]\s*(?:#.*)?$') if (-not $match.Success) { throw "Line $Number of the front matter has a list that is not closed with ]: $Text" } # A comma inside quotes belongs to the text. $pattern = '\s*(?<item>"(?:[^"\\]|\\.)*"|''(?:[^'']|'''')*''|[^,]*)\s*(?:,|$)' $items = [regex]::Matches($match.Groups['items'].Value, $pattern) $list = foreach ($item in $items) { if ($item.Length -gt 0 -and $item.Groups['item'].Value.Trim() -ne '') { & $readScalar $item.Groups['item'].Value $Number } } , @($list) } $result = [ordered]@{} $lines = $Yaml -replace '\r\n?', "`n" -split "`n" $index = 0 while ($index -lt $lines.Count) { $line = $lines[$index].Replace("`t", ' ') $number = $index + 1 $index++ if ($line.Trim() -eq '' -or $line.TrimStart().StartsWith('#')) { continue } $entry = [regex]::Match($line, '^(?<key>[A-Za-z_][A-Za-z0-9_-]*)\s*:(?:\s+(?<value>.*))?$') if (-not $entry.Success) { if ($line -match '^\s') { $hint = 'A value inside a value is not supported: write the front matter as JSON for that.' throw "Line $number of the front matter is indented but belongs to no list or block of text. $hint" } throw "Line $number of the front matter is not 'key: value': $($line.Trim())" } $key = $entry.Groups['key'].Value if ($result.Contains($key)) { throw "Line $number of the front matter sets '$key' a second time." } $rest = $entry.Groups['value'].Value.Trim() if ($rest -match '^[|>][+-]?\s*(?:#.*)?$') { # A block of text: the lines below that are indented. $block = [System.Collections.Generic.List[string]]::new() while ($index -lt $lines.Count) { $next = $lines[$index].Replace("`t", ' ') if ($next.Trim() -ne '' -and $next -notmatch '^\s') { break } $block.Add($next) $index++ } $indents = @( $block | Where-Object { $_.Trim() -ne '' } | ForEach-Object { $_.Length - $_.TrimStart().Length } ) $indent = if ($indents.Count -gt 0) { ($indents | Measure-Object -Minimum).Minimum } else { 0 } $text = @( foreach ($item in $block) { if ($item.Trim() -eq '') { '' } else { $item.Substring($indent).TrimEnd() } } ) if ($rest.StartsWith('|')) { $result[$key] = ($text -join "`n").Trim("`n") } else { # Lines are joined with a space; an empty line starts a new paragraph. $paragraphs = ($text -join "`n").Trim("`n") -split "`n{2,}" $result[$key] = ($paragraphs | ForEach-Object { ($_ -split "`n") -join ' ' }) -join "`n" } continue } if ($rest.StartsWith('[')) { $result[$key] = & $readFlowList $rest $number continue } if ($rest -eq '' -or $rest.StartsWith('#')) { # Nothing on the line itself: a list on the lines below, or an empty value. $list = [System.Collections.Generic.List[object]]::new() $isList = $false while ($index -lt $lines.Count) { $next = $lines[$index].Replace("`t", ' ') if ($next.Trim() -eq '' -or $next.TrimStart().StartsWith('#')) { $index++ continue } $item = [regex]::Match($next, '^\s*-(?:\s+(?<value>.*))?$') if (-not $item.Success) { break } $itemText = $item.Groups['value'].Value if ($itemText -match '^[A-Za-z_][A-Za-z0-9_-]*:(?:\s|$)') { $hint = 'Put the text in quotes, or write the front matter as JSON for a value inside a value.' throw "Line $($index + 1) of the front matter has a list item with a value inside: $itemText. $hint" } $list.Add((& $readScalar $itemText ($index + 1))) $isList = $true $index++ } if ($isList) { $result[$key] = $list.ToArray() } else { if ($index -lt $lines.Count -and $lines[$index] -match '^\s+\S') { $hint = 'A value inside a value is not supported: write the front matter as JSON for that.' throw "Line $($index + 1) of the front matter is a value inside '$key'. $hint" } $result[$key] = '' } continue } $result[$key] = & $readScalar $rest $number } $result } |