Public/Sync-GhostPage.ps1
|
function Sync-GhostPage { <# .SYNOPSIS Creates or updates pages on the Ghost site from Markdown files. .DESCRIPTION Makes the page on the site match a Markdown file, which is what a pipeline needs to publish pages from a repository. A file starts with front matter between two lines of three dashes, followed by the Markdown of the page: --- title: My page tags: [News, Releases] custom_excerpt: Shown in lists --- # Heading The keys of the front matter are the fields of a page in the Ghost API, such as title, status, tags, custom_excerpt and feature_image. The parameter names of New-GhostPage, 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 page. It comes from the front matter or, without one there, from the name of the file: my-page.md is the page with the slug my-page. A file that is named index.md takes the name of its folder, so that a page can have a folder of its own, with its images next to it: my-page/index.md. A date at the start of the name, 2026-11-20-my-page, is not a part of the slug: it is the publication date of the page, 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 page on every machine. A page with that slug is updated; when there is none, the page is created, for which the front matter needs a title. A page is only updated when the file differs from the page, 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 page is a draft and an existing page keeps its status, and "status": "published" publishes the page. A page that a route of the theme shows, with data: page.my-page in routes.yaml, has to exist before the route works: this is how such a page gets to every site that has the theme. Export-GhostPage writes these files from the pages of a site. An image can be a file next to the page. 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 page gets its address. It is uploaded once: as long as the file does not change, the page 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 page, and an image that is no longer used stays on the site: Ghost cannot remove an image through its API. .EXAMPLE Sync-GhostPage -Path ./pages Creates or updates a page for every .md file in the folder pages. .EXAMPLE Sync-GhostPage -Path ./pages -Recurse -WhatIf Shows which pages would be created or updated for the files in pages and the folders below it, such as pages/my-page/index.md. .EXAMPLE Sync-GhostPage -Path ./pages/about/index.md Creates or updates the page with the slug about. .LINK https://docs.ghost.org/admin-api/pages/creating-a-page .LINK https://docs.ghost.org/admin-api/pages/updating-a-page .LINK https://docs.ghost.org/admin-api/images/uploading-an-image #> [CmdletBinding(SupportsShouldProcess)] [OutputType('Ghost.PageSync')] 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 pages that have a folder of their own. [switch] $Recurse, # Update a page even when the file does not differ from it. [switch] $Force ) begin { Test-GhostConnection # Everything a page can be given, except its content, which is the Markdown of the file, and the # updated_at value, which is taken from the page on the site. $body = (Get-GhostAPIData -Endpoint 'Set-GhostPage').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) { # A README says what a folder is for; it is not a page. Get-ChildItem -LiteralPath $entry.FullName -File -Recurse:$Recurse | Where-Object { $_.Extension -eq '.md' -and $_.BaseName -ne 'README' } } 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-GhostPage -Filter "slug:'$slug'") | Select-Object -First 1 # The image files the page refers to. One that the page on the site already has, unchanged, # comes with its address; the others are uploaded once it is certain that the page is saved. $images = @(Get-GhostPostImage -Source $source -Post $result) $pending = @($images | Where-Object { -not $_.Url }) $content = Convert-GhostPostImage -Source $source -Images $images $page = $content.Parameters if (-not $result) { if ([string]::IsNullOrWhiteSpace([string] $page['Title'])) { throw "There is no page with the slug '$slug' yet, and creating it needs a title." } $action = 'Created' $operation = "Create the page '$slug'" } else { $comparison = @{ Post = $result Parameters = $page 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 page '$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 $page = $content.Parameters } if ($action -eq 'Created') { $result = New-GhostPage @page -Markdown $content.Markdown -Confirm:$false if ($result.slug -cne $slug) { # Ghost picks another slug when this one is taken, by a post for example. The # page would not be found on the next run and be created again, so it is taken # back. Remove-GhostPage -Id $result.id -Confirm:$false $stored = "Ghost cannot use the slug '$slug': it stored the page as" $advice = 'The slug is probably taken by a post. Choose another slug.' throw "$stored '$($result.slug)'. $advice" } } else { # The updated_at value of the page as it was just read: when somebody saves the page # in between, Ghost refuses the update instead of overwriting that change. $current = @{ Id = $result.id UpdatedAt = $result.updated_at } $result = Set-GhostPage @current @page -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.PageSync' 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 = 'GhostPageFileError' 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) } } } } } |