Public/Sync-GhostPost.ps1
|
function Sync-GhostPost { <# .SYNOPSIS Creates or updates posts on the Ghost site from Markdown files. .DESCRIPTION Makes the post on the site match a Markdown file, which is what a pipeline needs to publish posts from a repository. A file starts with front matter, a JSON object between two lines of three dashes, followed by the Markdown of the post: --- { "title": "My post", "tags": ["News"], "custom_excerpt": "Shown in lists" } --- # Heading The keys of the front matter are the fields of a post in the Ghost API, such as title, status, tags, custom_excerpt and feature_image. The parameter names of New-GhostPost, such as CustomExcerpt, work too. The slug identifies the post. It comes from the front matter or, without one there, from the name of the file: my-post.md is the post with the slug my-post. A post with that slug is updated; when there is none, the post is created, for which the front matter needs a title. A post is only updated when the file differs from the post, so the command can run for every file on every push. Fields that the front matter does not mention are left as they are on the site. The Markdown is stored as it is, in a Markdown card, and rendered by Ghost. The status in the front matter is followed: without one a new post is a draft and an existing post keeps its status, and "status": "published" publishes the post. An email is never sent. To send a post to a newsletter, leave the status out of the file and pipe the result to Publish-GhostPost. An image can be a file next to the post. Refer to it by its path, relative to the folder of the Markdown file, in the Markdown, , or in the front matter as feature_image, og_image or twitter_image. The file is uploaded and the post gets its address. It is uploaded once: as long as the file does not change, the post keeps the image it has. An address (https://...) is left as it is. The addresses of the images that were uploaded are in the property UploadedImages of the result. Removing a file does not remove the post, and an image that is no longer used stays on the site: Ghost cannot remove an image through its API. .EXAMPLE Sync-GhostPost -Path ./posts Creates or updates a post for every .md file in the folder posts. .EXAMPLE Get-ChildItem -Path ./posts -Filter *.md -Recurse | Sync-GhostPost -WhatIf Shows which posts would be created or updated for the files in posts and the folders below it. .EXAMPLE Sync-GhostPost -Path ./posts/weekly-update.md | Publish-GhostPost -Newsletter 'weekly' Creates or updates the post and then publishes it and sends it to the newsletter weekly. .LINK https://docs.ghost.org/admin-api/posts/creating-a-post .LINK https://docs.ghost.org/admin-api/posts/updating-a-post .LINK https://docs.ghost.org/admin-api/images/uploading-an-image #> [CmdletBinding(SupportsShouldProcess)] [OutputType('Ghost.PostSync')] param( # Markdown files, or folders of which every .md file is used. Wildcards are allowed. [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('FullName')] [ValidateNotNullOrEmpty()] [string[]] $Path, # Update a post even when the file does not differ from it. [switch] $Force ) begin { Test-GhostConnection # Everything a post can be given, except its content, which is the Markdown of the file, and the # updated_at value, which is taken from the post on the site. $body = (Get-GhostAPIData -Endpoint 'Set-GhostPost').Body $fields = @{} foreach ($name in $body.Keys) { if (@('Lexical', 'Html', 'UpdatedAt') -notcontains $name) { $fields[$name] = $body[$name] } } } process { foreach ($item in $Path) { # A path that exists is taken literally, so that brackets in a file name are not read as wildcards. $found = if (Test-Path -LiteralPath $item) { Get-Item -LiteralPath $item } else { Get-Item -Path $item } $files = foreach ($entry in $found) { if ($entry.PSIsContainer) { Get-ChildItem -LiteralPath $entry.FullName -File | Where-Object { $_.Extension -eq '.md' } } else { $entry } } foreach ($file in $files | Sort-Object -Property FullName) { try { $source = Read-GhostPostFile -Path $file.FullName -Fields $fields $slug = $source.Parameters['Slug'] $action = 'Unchanged' $operation = $null $uploaded = @() # Quoted, so that a slug of digits only is compared as text. $result = @(Get-GhostPost -Filter "slug:'$slug'") | Select-Object -First 1 # The image files the post refers to. One that the post on the site already has, unchanged, # comes with its address; the others are uploaded once it is certain that the post is saved. $images = @(Get-GhostPostImage -Source $source -Post $result) $pending = @($images | Where-Object { -not $_.Url }) $content = Convert-GhostPostImage -Source $source -Images $images $post = $content.Parameters if (-not $result) { if ([string]::IsNullOrWhiteSpace([string] $post['Title'])) { throw "There is no post with the slug '$slug' yet, and creating it needs a title." } $action = 'Created' $operation = "Create the post '$slug'" } else { $comparison = @{ Post = $result Parameters = $post Fields = $fields Markdown = $content.Markdown } # An image that has to be uploaded is a change by itself: it is new, or its file changed. if ($Force -or $pending.Count -gt 0 -or (Test-GhostPostChange @comparison)) { $action = 'Updated' $operation = "Update the post '$slug'" } } if ($operation) { $count = @($pending | ForEach-Object { $_.Name } | Select-Object -Unique).Count if ($count -gt 0) { $noun = if ($count -eq 1) { 'image' } else { 'images' } $operation = '{0} and upload {1} {2}' -f $operation, $count, $noun } if (-not $PSCmdlet.ShouldProcess($file.FullName, $operation)) { continue } foreach ($image in $pending) { # Uploaded a moment ago, for an earlier reference to the same file. if ($image.Url) { continue } Write-Verbose -Message "Uploading $($image.Path) as $($image.Name)" $upload = @{ Path = $image.Path Name = $image.Name Reference = $image.Destination } $imageUrl = (New-GhostImage @upload -Confirm:$false).url $uploaded += $imageUrl foreach ($other in $pending) { if ($other.Name -ceq $image.Name) { $other.Url = $imageUrl } } } if ($pending.Count -gt 0) { $content = Convert-GhostPostImage -Source $source -Images $images $post = $content.Parameters } if ($action -eq 'Created') { $result = New-GhostPost @post -Markdown $content.Markdown -Confirm:$false if ($result.slug -cne $slug) { # Ghost picks another slug when this one is taken, by a page for example. The # post would not be found on the next run and be created again, so it is taken # back. Remove-GhostPost -Id $result.id -Confirm:$false $stored = "Ghost cannot use the slug '$slug': it stored the post as" $advice = 'The slug is probably taken by a page. Choose another slug.' throw "$stored '$($result.slug)'. $advice" } } else { # The updated_at value of the post as it was just read: when somebody saves the post # in between, Ghost refuses the update instead of overwriting that change. $current = @{ Id = $result.id UpdatedAt = $result.updated_at } $result = Set-GhostPost @current @post -Markdown $content.Markdown -Confirm:$false } } # Outside the hash literal: Windows PowerShell cannot parse an if statement as a value in one. $url = $result.PSObject.Properties['url'] $address = if ($url) { $url.Value } else { $null } [pscustomobject]@{ PSTypeName = 'Ghost.PostSync' Action = $action Status = $result.status Slug = $result.slug Title = $result.title Id = $result.id Url = $address Path = $file.FullName UploadedImages = @($uploaded) } } catch { # Says which file the error is about. An error from Ghost keeps its id, such as ValidationError, # which is the part before the comma. A problem with the file itself was thrown as a message # and has that message for an id. $errorId = 'GhostPostFileError' if ($_.FullyQualifiedErrorId -ne $_.Exception.Message) { $errorId = $_.FullyQualifiedErrorId.Split(',')[0] } $message = '{0}: {1}' -f $file.FullName, $_.Exception.Message $exception = [System.InvalidOperationException]::new($message, $_.Exception) $record = [System.Management.Automation.ErrorRecord]::new( $exception, $errorId, $_.CategoryInfo.Category, $file.FullName ) $PSCmdlet.ThrowTerminatingError($record) } } } } } |