Private/Read-GhostPostFile.ps1

function Read-GhostPostFile {
    <#
    .SYNOPSIS
        Reads a Markdown file with front matter and returns the post it describes.

    .DESCRIPTION
        The file starts with front matter between two lines of three dashes. The Markdown below it is the content
        of the post. Front matter is written in YAML, the way most tools for Markdown do it,

            ---
            title: My post
            tags: [News, Releases]
            custom_excerpt: Shown in lists
            ---

            # Heading

        or as a JSON object, { "title": "My post", "tags": ["News"] }, which is needed for a value inside a
        value, such as a tag with a description of its own. ConvertFrom-FrontMatterYaml describes the YAML that
        is read.

        A key of the front matter is the name of a field of the Ghost API, such as custom_excerpt, or the name of
        the matching parameter of New-GhostPost, such as CustomExcerpt. An unknown key is an error, so that a typo
        does not go unnoticed.

        The slug identifies the post on the site. Without a slug in the front matter it comes from the name of
        the file, my-post.md, or, for a file that is named index.md, from the name of its folder: my-post/index.md.
        A date at the start of that 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 of its own.

        The slug has to be in the form Ghost stores slugs in, lower case letters, digits and hyphens, because
        Ghost would change any other slug and the post would not be found again.

        A publication date without a time zone is read as UTC, and a date without a time as the start of that
        day in UTC, so that the same file gives the same post on every machine.

        The file is read as UTF-8. Line endings are normalized to line feeds and empty lines around the Markdown
        are removed, so that the same file gives the same post on every platform.

    .EXAMPLE
        Read-GhostPostFile -Path ./posts/my-post.md -Fields $fields

        Returns an object with the path, the parameters for New-GhostPost or Set-GhostPost, and the Markdown.

    .EXAMPLE
        Read-GhostPostFile -Path ./posts/2026-11-20-my-post/index.md -Fields $fields

        Returns the post with the slug my-post and the publication date 20 November 2026.
    #>

    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param(
        # Full path of the Markdown file.
        [Parameter(Mandatory)]
        [string] $Path,

        # The fields the front matter may set: parameter name = name of the field in the Ghost API.
        [Parameter(Mandatory)]
        [System.Collections.IDictionary] $Fields
    )

    $text = [System.IO.File]::ReadAllText($Path, [System.Text.Encoding]::UTF8)
    $pattern = '(?s)\A---[ \t]*\r?\n(?<frontMatter>.*?)\r?\n---[ \t]*(?:\r?\n(?<markdown>.*))?\z'
    $match = [regex]::Match($text, $pattern)
    if (-not $match.Success) {
        throw "$Path does not start with front matter: 'key: value' lines between two lines of three dashes (---)."
    }

    # The front matter as a list of keys and values, in the order of the file.
    $frontMatter = $match.Groups['frontMatter'].Value
    $entries = [ordered]@{}
    if ($frontMatter.TrimStart() -match '^[{\[]') {
        try {
            $metadata = ConvertFrom-Json -InputObject $frontMatter
        }
        catch {
            throw "The front matter of $Path is not valid JSON: $($_.Exception.Message)"
        }
        # The full type name: [pscustomobject] stands for PSObject, which also matches a list on Windows PowerShell.
        if ($metadata -isnot [System.Management.Automation.PSCustomObject]) {
            throw "The front matter of $Path has to be a JSON object: { ... }."
        }
        foreach ($property in $metadata.PSObject.Properties) {
            # JSON keeps keys apart that only differ in case; the fields do not.
            if ($entries.Contains($property.Name)) {
                throw "The front matter of $Path sets $($property.Name) twice."
            }
            $entries[$property.Name] = $property.Value
        }
    }
    else {
        try {
            $entries = ConvertFrom-FrontMatterYaml -Yaml $frontMatter
        }
        catch {
            throw "The front matter of $Path cannot be read. $($_.Exception.Message)"
        }
    }

    # Both the name of the parameter and the name of the field lead to the parameter.
    $names = @{}
    foreach ($name in $Fields.Keys) {
        $names[$name] = $name
        $names[$Fields[$name]] = $name
    }

    $parameters = @{}
    foreach ($key in $entries.Keys) {
        $name = $names[$key]
        if (-not $name) {
            $known = @($Fields.Values | Sort-Object) -join ', '
            throw "The front matter of $Path has the unknown key '$key'. Known keys: $known."
        }
        if ($parameters.ContainsKey($name)) {
            throw "The front matter of $Path sets $($Fields[$name]) twice."
        }
        $parameters[$name] = $entries[$key]
    }

    # The name the post goes by: that of the file or, for index.md, that of its folder.
    $fileName = [System.IO.Path]::GetFileNameWithoutExtension($Path)
    if ($fileName -eq 'index') {
        $fileName = [System.IO.Path]::GetFileName([System.IO.Path]::GetDirectoryName($Path))
    }
    $nameDate = $null
    if ($fileName -match '^(?<date>\d{4}-\d{2}-\d{2})-(?<name>.+)$') {
        $nameDate = $Matches['date']
        $fileName = $Matches['name']
    }

    if (-not $parameters.ContainsKey('Slug') -or [string]::IsNullOrWhiteSpace([string] $parameters['Slug'])) {
        $parameters['Slug'] = $fileName
    }
    $slug = [string] $parameters['Slug']
    if ($slug -cnotmatch '^[a-z0-9]+(?:-[a-z0-9]+)*$' -or $slug.Length -gt 185) {
        $advice = 'Use lower case letters, digits and hyphens: rename the file or set "slug" in its front matter.'
        throw "'$slug' cannot be the slug of the post in $Path. $advice"
    }
    $parameters['Slug'] = $slug

    # The publication date, as a moment in UTC whatever the time zone of this machine.
    if ($Fields.Keys -contains 'PublishedAt') {
        $publishedAt = $null
        if ($parameters.ContainsKey('PublishedAt')) {
            $publishedAt = $parameters['PublishedAt']
        }
        elseif ($nameDate) {
            $publishedAt = $nameDate
        }

        if ($publishedAt -is [datetime]) {
            # JSON with a time zone is read as that moment already. Without one, the time is taken as UTC.
            if ($publishedAt.Kind -eq [System.DateTimeKind]::Unspecified) {
                $publishedAt = [datetime]::SpecifyKind($publishedAt, [System.DateTimeKind]::Utc)
            }
            $parameters['PublishedAt'] = $publishedAt.ToUniversalTime()
        }
        elseif (-not [string]::IsNullOrWhiteSpace([string] $publishedAt)) {
            $moment = [datetimeoffset]::MinValue
            $styles = [System.Globalization.DateTimeStyles]::AssumeUniversal
            $culture = [cultureinfo]::InvariantCulture
            if (-not [datetimeoffset]::TryParse([string] $publishedAt, $culture, $styles, [ref] $moment)) {
                $form = 'Write it as 2026-11-20 or, with a time, as 2026-11-20T08:30:00Z.'
                throw "The publication date '$publishedAt' of the post in $Path cannot be read. $form"
            }
            $parameters['PublishedAt'] = $moment.UtcDateTime
        }
    }

    [pscustomobject]@{
        Path       = $Path
        Parameters = $parameters
        Markdown   = ($match.Groups['markdown'].Value -replace '\r\n?', "`n").Trim("`n")
    }
}