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, 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 tag that a file there describes, and that no file in Path describes any more, is removed from the site. Tags are compared by their slug. Ghost takes a removed tag off its posts and keeps the posts. Removing cannot be undone, so the command asks for confirmation before it removes a tag. Nothing is removed when a file in Path fails. 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. 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 Returns which tags would be created or updated. Nothing is sent. .EXAMPLE Sync-GhostTag -Path ./tags/release-notes.md Creates or updates the tag with the slug release-notes. .EXAMPLE Sync-GhostTag -Path ./tags -PreviousPath ./before/tags -Confirm:$false Creates or updates the tags, and removes every tag that a file in before/tags describes and no file in tags 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 .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, # Files or folders with the files as they were at the previous run. A tag 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 tag even when the file does not differ from it. [switch] $Force ) begin { Test-GhostConnection Test-GhostPreviousPath -BoundParameters $PSBoundParameters $fields = (Get-GhostAPIData -Endpoint 'Set-GhostTag').Body # The slugs of the files in Path. A tag 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) { try { $source = Read-GhostPostFile -Path $file.FullName -Fields $fields $tag = $source.Parameters $slug = $tag['Slug'] $slugs.Add($slug) 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 } $action = 'Unchanged' $operation = $null $dryRun = $false # 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) { $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) { 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 } } # What the result says about the tag. Before a tag is created there is nothing on the site # to read, so the slug is that of the file. $row = @{ Name = $null Slug = $slug Id = $null } if ($result) { $row['Name'] = $result.name $row['Slug'] = $result.slug $row['Id'] = $result.id } if ($dryRun) { # Nothing was saved. The file says what the tag would be. $action = if ($action -eq 'Created') { 'WouldCreate' } else { 'WouldUpdate' } if ($tag.ContainsKey('Name')) { $row['Name'] = $tag['Name'] } } [pscustomobject]@{ PSTypeName = 'Ghost.TagSync' Action = $action Name = $row['Name'] Slug = $row['Slug'] Id = $row['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) } } } } end { if ($PSBoundParameters.ContainsKey('PreviousPath')) { try { $removal = @{ Kind = 'Tag' PreviousPath = $PreviousPath CurrentSlug = $slugs.ToArray() Fields = $fields } Remove-GhostSyncResource @removal } catch { $PSCmdlet.ThrowTerminatingError($_) } } } } |