Private/ConvertTo-GhostPostFile.ps1
|
function ConvertTo-GhostPostFile { <# .SYNOPSIS Returns the text of the Markdown file that describes a post or a page of the site. .DESCRIPTION Export-GhostPost and Export-GhostPage use this to write a file that Sync-GhostPost or Sync-GhostPage reads as the same post or page. The file starts with front matter that holds the title and every other field that has a value: the status, the tags, the excerpt, the images, the template and the fields for search engines. A visibility of public and the authors are left out. The slug is left out as well, because the name of the file or of its folder holds it. The content follows the front matter: - A post that was written as Markdown, in one or more Markdown cards, gives that Markdown back. - Any other post gives the HTML that Ghost renders for it, rewritten by ConvertTo-MarkdownHtmlBlock so that a Markdown card shows it as it is. The file has line feeds as line endings and ends with one. An image is written as its address. With -IncludeImage an image that was uploaded to a Ghost site is written as the path of a file instead, images/2026-11-diagram.png, in the three image fields of the front matter and wherever Get-MarkdownImage finds an image in the content. That is where Sync-GhostPost reads an image file. Get-GhostUploadedImage says which addresses those are and names the file. The property Images of the result lists these images, each with the address to fetch it from and its path, so that the caller can save the files. An HTML image that gets a path loses its srcset and sizes, which hold addresses of the same image in other widths. An address in -KnownImage gets the path that is given for it and is not listed: the image file of a post that came from a file, which Sync-GhostPost uploaded. An address in -ExcludeImage stays an address. .EXAMPLE ConvertTo-GhostPostFile -Post (Get-GhostPost -Slug 'my-post' -Formats lexical, html -Include tags) Returns the text of the file for that post, and whether its content was Markdown, Html or Empty. .EXAMPLE ConvertTo-GhostPostFile -Post $post -IncludeImage Returns the text with a path for every uploaded image, and those images in the property Images. #> [CmdletBinding()] [OutputType([pscustomobject])] param( # The post or the page, read with the formats lexical and html and with its tags. [Parameter(Mandatory)] [object] $Post, # Write an image that was uploaded to a Ghost site as the path of a file in the folder images. [switch] $IncludeImage, # Images that have a file already: the address as the post has it = the path as the file has it. [System.Collections.IDictionary] $KnownImage = @{}, # Addresses to leave as they are, as the property Images gave them: of images that cannot be saved. [string[]] $ExcludeImage = @() ) # The text fields, in the order of the front matter. $keys = @( 'custom_excerpt', 'feature_image', 'feature_image_alt', 'feature_image_caption', 'custom_template' 'canonical_url', 'meta_title', 'meta_description', 'og_image', 'og_title', 'og_description' 'twitter_image', 'twitter_title', 'twitter_description', 'codeinjection_head', 'codeinjection_foot' ) $imageKeys = 'feature_image', 'og_image', 'twitter_image' # The images that get a file: the address to fetch = the path. A name that is taken by another image gets # a number, in the order of the file. A path is compared without regard to case, as Windows does. $images = [System.Collections.Generic.List[object]]::new() $paths = [System.Collections.Generic.Dictionary[string, string]]::new([System.StringComparer]::Ordinal) $taken = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($address in $KnownImage.Keys) { $path = ([string] $KnownImage[$address]) -replace '^\./', '' $taken.Add($path) | Out-Null } $excluded = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) foreach ($address in $ExcludeImage) { $excluded.Add($address) | Out-Null } # The path to write for an address, or nothing for an address that stays as it is. $resolve = { param($Address) if (-not $IncludeImage -or -not $Address) { return } if ($KnownImage.Keys -ccontains $Address) { return [string] $KnownImage[$Address] } $upload = Get-GhostUploadedImage -Url $Address if (-not $upload -or $excluded.Contains($upload.Url)) { return } if (-not $paths.ContainsKey($upload.Url)) { $extension = [System.IO.Path]::GetExtension($upload.Name) $stem = $upload.Name.Substring(0, $upload.Name.Length - $extension.Length) $path = 'images/{0}' -f $upload.Name $number = 1 while (-not $taken.Add($path)) { $number++ $path = 'images/{0}-{1}{2}' -f $stem, $number, $extension } $paths[$upload.Url] = $path $images.Add([pscustomobject]@{ Url = $upload.Url; Path = $path }) } $paths[$upload.Url] } # Text in double quotes can hold anything, once a backslash, a quote and the line ends are escaped. $quote = { param($Text) $escaped = $Text.Replace('\', '\\').Replace('"', '\"') '"{0}"' -f $escaped.Replace("`r", '\r').Replace("`n", '\n').Replace("`t", '\t') } # The value of a property that may not be there. $read = { param($Object, $Name) $property = $Object.PSObject.Properties[$Name] if ($property) { $property.Value } } $lines = [System.Collections.Generic.List[string]]::new() $lines.Add('---') $lines.Add(('title: {0}' -f (& $quote ([string] $Post.title)))) $lines.Add(('status: {0}' -f $Post.status)) $visibility = [string] (& $read $Post 'visibility') if ($visibility -and $visibility -ne 'public') { $lines.Add(('visibility: {0}' -f (& $quote $visibility))) } if ((& $read $Post 'featured') -eq $true) { $lines.Add('featured: true') } $tags = @(& $read $Post 'tags' | Where-Object { $_ } | ForEach-Object { & $quote ([string] $_.name) }) if ($tags.Count -gt 0) { $lines.Add(('tags: [{0}]' -f ($tags -join ', '))) } # A date is a [datetime] on PowerShell 7 and text on Windows PowerShell. $publishedAt = & $read $Post 'published_at' if ($publishedAt -is [datetime]) { $format = 'yyyy-MM-ddTHH:mm:ss.fffZ' $publishedAt = $publishedAt.ToUniversalTime().ToString($format, [cultureinfo]::InvariantCulture) } if ($publishedAt) { $lines.Add(('published_at: {0}' -f (& $quote ([string] $publishedAt)))) } foreach ($key in $keys) { $value = [string] (& $read $Post $key) if ($value -and $imageKeys -contains $key) { $path = & $resolve $value if ($path) { $value = $path } } if ($value) { $lines.Add(('{0}: {1}' -f $key, (& $quote $value))) } } $lines.Add('---') # The content: the Markdown of the post when it is made of Markdown cards, its HTML otherwise. $kind = 'Empty' $body = '' $children = $null $lexical = [string] (& $read $Post 'lexical') if ($lexical) { try { $children = @((ConvertFrom-Json -InputObject $lexical).root.children | Where-Object { $_ }) } catch { Write-Debug -Message "The content cannot be read: $($_.Exception.Message)" } } $other = @($children | Where-Object { $_ -and $_.type -ne 'markdown' }) if ($null -ne $children -and $children.Count -gt 0 -and $other.Count -eq 0) { $kind = 'Markdown' $body = @($children | ForEach-Object { [string] $_.markdown }) -join "`n`n" } elseif ($null -eq $children -or $children.Count -gt 0) { $html = ConvertTo-MarkdownHtmlBlock -Html ([string] (& $read $Post 'html')) if ($html) { $kind = 'Html' $body = $html } } $body = ($body -replace '\r\n?', "`n").Trim("`n") if ($IncludeImage -and $body) { # In the order of the text first, so that the names are given in that order. Then from the end to the # start, so that the positions before a change stay right. $found = @( foreach ($image in Get-MarkdownImage -Markdown $body) { $path = & $resolve $image.Destination if ($path) { [pscustomobject]@{ Index = $image.Index; Length = $image.Length; Path = $path } } } ) $ignoreCase = [System.Text.RegularExpressions.RegexOptions]::IgnoreCase $tag = [regex]::new('\G<img\b(?:[^>"'']|"[^"]*"|''[^'']*'')*>', $ignoreCase) $attribute = '\s+(?<name>[^\s=>"''/]+)(?:\s*=\s*(?:"[^"]*"|''[^'']*''|[^\s"''>]+))?' $withoutWidths = [System.Text.RegularExpressions.MatchEvaluator] { param($Match) if (@('srcset', 'sizes') -contains $Match.Groups['name'].Value) { '' } else { $Match.Value } } foreach ($image in $found | Sort-Object -Property Index -Descending) { # The HTML image this destination is in, when it is in one. $start = $body.LastIndexOf('<', $image.Index) $element = $null if ($start -ge 0) { $element = $tag.Match($body, $start) } if ($element -and $element.Success -and $element.Index + $element.Length -gt $image.Index) { $text = $element.Value $text = $text.Remove($image.Index - $start, $image.Length).Insert($image.Index - $start, $image.Path) $text = [regex]::Replace($text, $attribute, $withoutWidths, $ignoreCase) $body = $body.Remove($start, $element.Length).Insert($start, $text) } else { $body = $body.Remove($image.Index, $image.Length).Insert($image.Index, $image.Path) } } } if ($body) { $lines.Add('') $lines.Add($body) } [pscustomobject]@{ Text = ($lines -join "`n") + "`n" Content = $kind Images = @($images) } } |