Public/Sync-GhostTag.ps1
|
function Sync-GhostTag { <# .SYNOPSIS Creates or updates tags on the Ghost site from files. .DESCRIPTION Makes the tag on the site match a file, so that the tags of a site can be kept in a repository, next to its posts, and be the same on every site that is made from it. A file starts with front matter between two lines of three dashes. The text below it is the description of the tag: --- name: Release notes accent_color: "#ff5500" meta_title: Release notes of the module --- What changed, version by version. The keys of the front matter are the fields of a tag in the Ghost API, such as name, accent_color, feature_image and meta_description. The parameter names of New-GhostTag, such as AccentColor, work too. The description can be a key of the front matter as well, but not in both places. The slug identifies the tag. It comes from the front matter or, without one there, from the name of the file: release-notes.md is the tag with the slug release-notes. A tag with that slug is updated; when there is none, the tag is created, for which the front matter needs a name. A tag is only updated when the file differs from the tag, so the command can run on every push. Fields that the file does not mention are left as they are on the site: to clear the description, write description: "" in the front matter. An image is an address; a file is not uploaded. Run it before Sync-GhostPost. A post that names a tag that does not exist creates it, with nothing but that name. Removing a file does not remove the tag. Export-GhostTag writes these files from the tags of a site. .EXAMPLE Sync-GhostTag -Path ./tags Creates or updates a tag for every .md file in the folder tags. .EXAMPLE Sync-GhostTag -Path ./tags -WhatIf Shows which tags would be created or updated. .EXAMPLE Sync-GhostTag -Path ./tags/release-notes.md Creates or updates the tag with the slug release-notes. .LINK https://docs.ghost.org/admin-api .LINK https://docs.ghost.org/content-api/tags #> [CmdletBinding(SupportsShouldProcess)] [OutputType('Ghost.TagSync')] param( # Tag 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, # Update a tag even when the file does not differ from it. [switch] $Force ) begin { Test-GhostConnection $fields = (Get-GhostAPIData -Endpoint 'Set-GhostTag').Body } 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 tag. Get-ChildItem -LiteralPath $entry.FullName -File | 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 $tag = $source.Parameters if ($source.Markdown) { if ($tag.ContainsKey('Description')) { throw 'The description is in the front matter and below it. Keep one of the two.' } $tag['Description'] = $source.Markdown } $slug = $tag['Slug'] $action = 'Unchanged' $operation = $null # Quoted, so that a slug of digits only is compared as text. $result = @(Get-GhostTag -Filter "slug:'$slug'") | Select-Object -First 1 if (-not $result) { if (-not $tag.ContainsKey('Name') -or [string]::IsNullOrWhiteSpace([string] $tag['Name'])) { throw "There is no tag with the slug '$slug' yet, and creating it needs a name." } $action = 'Created' $operation = "Create the tag '$slug'" } else { # A field that is empty on the site is null there and empty text in a file. $differs = $Force.IsPresent foreach ($name in $tag.Keys) { $property = $result.PSObject.Properties[$fields[$name]] $current = if ($property) { [string] $property.Value } else { '' } if ($current -cne [string] $tag[$name]) { $differs = $true } } if ($differs) { $action = 'Updated' $operation = "Update the tag '$slug'" } } if ($operation) { if (-not $PSCmdlet.ShouldProcess($file.FullName, $operation)) { continue } if ($action -eq 'Created') { $result = New-GhostTag @tag -Confirm:$false if ($result.slug -cne $slug) { # Ghost picks another slug when this one cannot be used. The tag would not be # found on the next run and be created again, so it is taken back. Remove-GhostTag -Id $result.id -Confirm:$false $stored = "Ghost cannot use the slug '$slug': it stored the tag as" throw "$stored '$($result.slug)'. Choose another slug." } } else { $result = Set-GhostTag -Id $result.id @tag -Confirm:$false } } [pscustomobject]@{ PSTypeName = 'Ghost.TagSync' Action = $action Name = $result.name Slug = $result.slug Id = $result.id Path = $file.FullName } } 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 = 'GhostTagFileError' 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) } } } } } |