Private/Save-GhostPostFile.ps1
|
function Save-GhostPostFile { <# .SYNOPSIS Writes the file of a post or a page and saves its images, as Compare-GhostPostFile said. .DESCRIPTION Export-GhostPost and Export-GhostPage call this once the caller agreed to the change. The images come first. An image that cannot be saved gives a warning and keeps its address in the file, so that the file never points at an image that is not there. The next export tries that image again. The file is written when it is not there yet or when its text changes. The answer has the action that was taken, Created, Updated or Unchanged, and the paths of the images that were saved. .EXAMPLE Save-GhostPostFile -Post $post -Change (Compare-GhostPostFile -Post $post -Path $file -Fields $fields) Writes the file when Compare-GhostPostFile found that it has to be written. #> [CmdletBinding()] [OutputType([pscustomobject])] param( # The post or the page, as it was given to Compare-GhostPostFile. [Parameter(Mandatory)] [object] $Post, # What Compare-GhostPostFile returned for it. [Parameter(Mandatory)] [object] $Change ) $saved = @() $failed = @() foreach ($image in $Change.Images) { try { Save-GhostImage -Url $image.Url -Path $image.Path $saved += $image.Path } catch { $failed += $image.Url $what = "The image $($image.Url) was not saved and keeps its address in $($Change.Path)" Write-Warning -Message "$what. $($_.Exception.Message)" } } $text = $Change.Text if ($failed.Count -gt 0) { $without = @{ Post = $Post IncludeImage = $true KnownImage = $Change.Known ExcludeImage = $failed } $text = (ConvertTo-GhostPostFile @without).Text } $action = 'Unchanged' if ($null -eq $Change.Existing) { $action = 'Created' } elseif ($Change.Existing -cne $text -and ($Change.Write -or $Change.Images.Count -gt 0)) { $action = 'Updated' } if ($action -ne 'Unchanged') { [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($Change.Path)) | Out-Null [System.IO.File]::WriteAllText($Change.Path, $text, [System.Text.UTF8Encoding]::new($false)) } [pscustomobject]@{ Action = $action SavedImages = @($saved) } } |