Public/Export-GhostPost.ps1
|
function Export-GhostPost { <# .SYNOPSIS Writes posts of the Ghost site to Markdown files, one folder per post. .DESCRIPTION Saves posts of the site as files that Sync-GhostPost reads, so that posts that were written in Ghost Admin can be kept in a repository and be given to another site, such as one on your own machine. A post becomes <date>-<slug>/index.md in the folder, where the date is the day the post was published, in UTC. A post without a publication date becomes <slug>/index.md. A post that a file in the folder, or in a folder below it, already describes keeps that file, whatever its name is. So a file can be moved or renamed after it was written, as long as its post keeps its slug. The file starts with front matter that holds the title of the post and every other field that has a value: its status, tags, publication date, excerpt, images, template and the fields for search engines. The authors are left out. The content of the post follows: - 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. Markdown may contain HTML, so Sync-GhostPost can send it to a site, where it is stored in a Markdown card. Such a post looks the same in most cases, but it is no longer made of the cards of the editor. The HTML is written without empty lines, because Markdown stops reading HTML at an empty line. An empty line in a code block is kept. The line break before it is written as a character reference, which a browser reads as that line break. The property Content of the result says which of the two a post was: Markdown, Html or Empty. The property Visibility says who may read the post on the site: public, members, paid or tiers. The file of a post holds all of its content, also when the site shows it to members only. An image is written as its address, and stays on the site it is on. A file that is the same as the post already is left alone. A file that differs is only overwritten with -Force. Without it the file is reported as Skipped, with a warning. A file whose post is no longer on the site is not removed. Pass a filter to write the posts that were made in Ghost Admin and no others. A post that came from a file differs from what this command writes for it, in the addresses of its images for one, and would be reported as Skipped. .EXAMPLE Export-GhostPost -Path ./posts -Filter 'tag:news' Writes a file for every post with the tag news that has none yet in the folder posts. .EXAMPLE Export-GhostPost -Path ./posts -Filter 'tag:hash-lesson+status:published' -Force Writes the published posts with the internal tag #lesson, and overwrites the files that differ from their post. The slug of an internal tag starts with hash- where its name starts with #. .EXAMPLE Export-GhostPost -Path ./posts Writes a file for every post of the site that has none yet. .LINK https://docs.ghost.org/admin-api/posts/overview #> [CmdletBinding(SupportsShouldProcess)] [OutputType('Ghost.PostSync')] param( # Folder for the posts. Created when it is not there. [Parameter(Mandatory, Position = 0)] [ValidateNotNullOrEmpty()] [string] $Path, # Which posts, as a filter of Ghost, such as tag:news or status:published. Defaults to every post. [string] $Filter, # Overwrite a file that differs from its post. [switch] $Force ) try { Test-GhostConnection $folder = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) # The files that are there already, by the slug of their post, read the way Sync-GhostPost reads them. $files = @{} if (Test-Path -LiteralPath $folder -PathType Container) { $body = (Get-GhostAPIData -Endpoint 'Set-GhostPost').Body $fields = @{} foreach ($name in $body.Keys) { if (@('Lexical', 'Html', 'UpdatedAt') -notcontains $name) { $fields[$name] = $body[$name] } } foreach ($existing in Get-GhostSyncFile -Path $folder -Recurse) { try { $source = Read-GhostPostFile -Path $existing.FullName -Fields $fields } catch { Write-Warning -Message "A file that is not read as a post is left alone. $($_.Exception.Message)" continue } $slug = [string] $source.Parameters['Slug'] if (-not $files.ContainsKey($slug)) { $files[$slug] = $existing.FullName } } } $query = @{ Formats = 'lexical', 'html' Include = 'tags' Order = 'slug asc' } if ($Filter) { $query['Filter'] = $Filter } foreach ($post in @(Get-GhostPost @query)) { $converted = ConvertTo-GhostPostFile -Post $post $content = $converted.Text $file = $files[[string] $post.slug] if (-not $file) { # A new file is named after the day of publication, which Sync-GhostPost does not take for a # part of the slug. A date is a [datetime] on PowerShell 7 and text on Windows PowerShell. $name = [string] $post.slug $day = $null $publishedAt = $post.PSObject.Properties['published_at'] if ($publishedAt -and $publishedAt.Value -is [datetime]) { $day = $publishedAt.Value.ToUniversalTime() } elseif ($publishedAt -and $publishedAt.Value) { $moment = [datetimeoffset]::MinValue $styles = [System.Globalization.DateTimeStyles]::AssumeUniversal $culture = [cultureinfo]::InvariantCulture if ([datetimeoffset]::TryParse([string] $publishedAt.Value, $culture, $styles, [ref] $moment)) { $day = $moment.UtcDateTime } } if ($day) { $name = '{0}-{1}' -f $day.ToString('yyyy-MM-dd', [cultureinfo]::InvariantCulture), $name } $file = Join-Path -Path (Join-Path -Path $folder -ChildPath $name) -ChildPath 'index.md' } $action = 'Created' if (Test-Path -LiteralPath $file) { $existing = [System.IO.File]::ReadAllText($file, [System.Text.Encoding]::UTF8) if (($existing -replace '\r\n?', "`n") -ceq $content) { $action = 'Unchanged' } elseif ($Force) { $action = 'Updated' } else { $action = 'Skipped' Write-Warning -Message "$file differs from the post '$($post.slug)'. Pass -Force to overwrite it." } } if (@('Created', 'Updated') -contains $action) { if (-not $PSCmdlet.ShouldProcess($file, "Write the post '$($post.slug)'")) { continue } New-Item -Path (Split-Path -Path $file -Parent) -ItemType Directory -Force | Out-Null [System.IO.File]::WriteAllText($file, $content, [System.Text.UTF8Encoding]::new($false)) } $row = @{ Url = $null Visibility = $null } foreach ($name in 'url', 'visibility') { $property = $post.PSObject.Properties[$name] if ($property) { $row[$name] = $property.Value } } [pscustomobject]@{ PSTypeName = 'Ghost.PostSync' Action = $action Status = $post.status Slug = $post.slug Title = $post.title Id = $post.id Url = $row['Url'] Path = $file UploadedImages = @() Content = $converted.Content Visibility = $row['Visibility'] } } } catch { $PSCmdlet.ThrowTerminatingError($_) } } |