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 between two lines of three dashes, followed by the Markdown of the post: --- title: My post tags: [News, Releases] 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. Front matter is YAML: text, true or false, lists, and text over several lines after | or >. A JSON object works as well, and is needed for a value inside a value, such as a tag with a description of its own. 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 file that is named index.md takes the name of its folder, so that a post can have a folder of its own, with its images next to it: my-post/index.md. A date at the start of the name, 2026-11-20-my-post, is not a part of the slug: it is the publication date of the post, unless the front matter has a published_at. A date without a time zone is read as UTC, so that the same file gives the same post on every machine. 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, unless PreviousPath says what the files were before. It holds the files as they were at the previous run, such as the previous commit of a repository. A post that a file there describes, and that no file in Path describes any more, is removed from the site. Posts are compared by their slug. A file that moved to another folder keeps its post. A file whose slug changed gives a new post, and the post with the old slug is removed. Removing cannot be undone, so the command asks for confirmation before it removes a post. Nothing is removed when a file in Path fails. An image that is no longer used stays on the site. Ghost cannot remove an image through its API. The property Action of a result says what was done: Created, Updated, Removed or Unchanged. With -WhatIf nothing is sent, and the action says what would be done: WouldCreate, WouldUpdate or WouldRemove. Such a result has the id of the post on the site when there is one, so do not pipe a dry run to a command that changes posts. .EXAMPLE Sync-GhostPost -Path ./posts Creates or updates a post for every .md file in the folder posts. .EXAMPLE Sync-GhostPost -Path ./posts -Recurse -WhatIf Returns which posts would be created or updated for the files in posts and the folders below it, such as posts/2026-11-20-my-post/index.md. Nothing is sent. .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. .EXAMPLE Sync-GhostPost -Path ./posts -Recurse -PreviousPath ./before/posts -Confirm:$false Creates or updates the posts, and removes every post that a file in before/posts describes and no file in posts describes any more. The folder before holds the previous commit, which git makes with git worktree add ./before HEAD~1. .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/posts/deleting-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, except a README.md. Wildcards are allowed. [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('FullName')] [ValidateNotNullOrEmpty()] [string[]] $Path, # Also use the .md files in the folders below a folder, for posts that have a folder of their own. [switch] $Recurse, # Files or folders with the files as they were at the previous run. A post that a file there describes, # and that no file in Path describes any more, is removed. Path has to name every current file then, so # this parameter cannot be used with files from the pipeline. [ValidateNotNullOrEmpty()] [string[]] $PreviousPath, # Update a post even when the file does not differ from it. [switch] $Force ) begin { Test-GhostConnection Test-GhostPreviousPath -BoundParameters $PSBoundParameters # 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] } } # The slugs of the files in Path. A post with one of these slugs is never removed. $slugs = [System.Collections.Generic.List[string]]::new() } process { foreach ($item in $Path) { foreach ($file in Get-GhostSyncFile -Path $item -Recurse:$Recurse) { try { $source = Read-GhostPostFile -Path $file.FullName -Fields $fields $slug = $source.Parameters['Slug'] $slugs.Add($slug) $action = 'Unchanged' $operation = $null $dryRun = $false $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 } $dryRun = -not $PSCmdlet.ShouldProcess($file.FullName, $operation) if ($dryRun -and -not $WhatIfPreference) { # The answer to the question was no. Nothing is done and nothing is reported. continue } } if ($operation -and -not $dryRun) { 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 } } # What the result says about the post. Before a post is created there is nothing on the # site to read, so the slug is that of the file. $row = @{ Status = $null Slug = $slug Title = $null Id = $null Url = $null } if ($result) { $row['Status'] = $result.status $row['Slug'] = $result.slug $row['Title'] = $result.title $row['Id'] = $result.id $url = $result.PSObject.Properties['url'] if ($url) { $row['Url'] = $url.Value } } if ($dryRun) { # Nothing was saved. The file says what the post would be. $action = if ($action -eq 'Created') { 'WouldCreate' } else { 'WouldUpdate' } if ($post.ContainsKey('Title')) { $row['Title'] = $post['Title'] } if ($post.ContainsKey('Status')) { $row['Status'] = $post['Status'] } elseif (-not $result) { $row['Status'] = 'draft' } } [pscustomobject]@{ PSTypeName = 'Ghost.PostSync' Action = $action Status = $row['Status'] Slug = $row['Slug'] Title = $row['Title'] Id = $row['Id'] Url = $row['Url'] 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) } } } } end { if ($PSBoundParameters.ContainsKey('PreviousPath')) { try { $removal = @{ Kind = 'Post' PreviousPath = $PreviousPath CurrentSlug = $slugs.ToArray() Fields = $fields Recurse = $Recurse } Remove-GhostSyncResource @removal } catch { $PSCmdlet.ThrowTerminatingError($_) } } } } |