KeepAChangelog.psm1

Set-StrictMode -Version Latest

# Source: src/public/Convert-ChangelogReleaseNotesToTagMessage.ps1
function Convert-ChangelogReleaseNotesToTagMessage {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyString()]
        [string]$ReleaseNotes
    )

    $lineList = [System.Collections.Generic.List[string]]::new()
    $allowBlankLine = $false

    foreach ($line in $ReleaseNotes -split '\r?\n') {
        $trimmedLine = $line.Trim()

        if ([string]::IsNullOrWhiteSpace($trimmedLine)) {
            $allowBlankLine = Add-ChangelogTagMessageBlankLine -LineList $lineList -AllowBlankLine $allowBlankLine
            continue
        }

        $lineList.Add((Get-ChangelogTagMessageLine -TrimmedLine $trimmedLine))
        $allowBlankLine = $true
    }

    $lineList = Get-TrimmedChangelogTagMessageLineList -LineList $lineList
    return ($lineList -join "`n").Trim()
}


# Source: src/public/Get-KeepAChangelogVersion.ps1
function Get-KeepAChangelogVersion {
    [CmdletBinding()]
    [OutputType([string])]
    param()

    return Get-KeepAChangelogModuleVersion
}


# Source: src/public/Initialize-KeepAChangelogFile.ps1
function Initialize-KeepAChangelogFile {
    [CmdletBinding(SupportsShouldProcess = $true)]
    param(
        [Parameter(Position = 0)]
        [string]$Path = 'CHANGELOG.md',

        [Parameter(Mandatory)]
        [string]$RepositoryUrl,

        [string]$PreviousReleaseReference,

        [string[]]$SectionHeading = @('Added', 'Changed', 'Deprecated', 'Removed', 'Fixed', 'Security'),

        [switch]$Force
    )

    dynamicparam {
        return Get-KeepAChangelogRepositoryProviderParameterDictionary -IncludeRepositoryTargetReference
    }

    begin {
        Assert-KeepAChangelogInitialization -Path $Path -RepositoryUrl $RepositoryUrl -Force $Force.IsPresent
        $normalizedRepositoryUrl = $RepositoryUrl.TrimEnd('/')
        $repositoryProvider = $PSBoundParameters['RepositoryProvider']
        $repositoryTargetReference = $PSBoundParameters['RepositoryTargetReference']
        $repositoryState = [pscustomobject]@{
            RepositoryUrl             = $normalizedRepositoryUrl
            RepositoryProvider        = $repositoryProvider
            RepositoryTargetReference = $repositoryTargetReference
            UnreleasedCompareLinkPrefix = ''
            UnreleasedTargetReference = ''
        }
        $template = Get-KeepAChangelogTemplateText `
            -RepositoryState $repositoryState `
            -PreviousReleaseReference $PreviousReleaseReference `
            -SectionHeading $SectionHeading

        if (-not $PSCmdlet.ShouldProcess($Path, 'Initialize Keep a Changelog template')) {
            return
        }

        Set-Content -LiteralPath $Path -Value $template -Encoding utf8 -NoNewline

        return [pscustomobject]@{
            Path                     = $Path
            RepositoryUrl            = $normalizedRepositoryUrl
            PreviousReleaseReference = if ([string]::IsNullOrWhiteSpace($PreviousReleaseReference)) { $null } else { $PreviousReleaseReference }
        }
    }
}


# Source: src/public/Move-UnreleasedChangelog.ps1
function Move-UnreleasedChangelog {
    [CmdletBinding(SupportsShouldProcess = $true)]
    param(
        [Parameter(Position = 0)]
        [string]$Path = 'CHANGELOG.md',

        [Parameter(Mandatory)]
        [string]$Version,

        [string]$Date,

        [string]$RepositoryUrl
    )

    dynamicparam {
        return Get-KeepAChangelogRepositoryProviderParameterDictionary `
            -IncludeRepositoryTargetReference `
            -IncludeReleaseReference
    }

    begin {
        if ([string]::IsNullOrWhiteSpace($Version)) {
            throw 'Version is required.'
        }

        if (-not (Test-Path -LiteralPath $Path)) {
            throw "Could not find CHANGELOG file at '$Path'."
        }

        $releaseDate = Resolve-KeepAChangelogReleaseDate -Date $Date
        $releaseReference = $PSBoundParameters['ReleaseReference']
        $release = @{
            Version   = $Version
            Date      = $releaseDate
            Tag       = $Version
            Reference = if ([string]::IsNullOrWhiteSpace($releaseReference)) { $Version } else { $releaseReference }
        }

        $repositoryProvider = $PSBoundParameters['RepositoryProvider']
        $repositoryTargetReference = $PSBoundParameters['RepositoryTargetReference']
        $repositoryState = Get-KeepAChangelogRepositoryState `
            -RepositoryUrl $RepositoryUrl `
            -RepositoryProvider $repositoryProvider `
            -RepositoryTargetReference $repositoryTargetReference
        $text = Get-Content -LiteralPath $Path -Raw
        $result = Resolve-KeepAChangelogReleaseData `
            -Text $text `
            -Release $release `
            -RepositoryState $repositoryState
        $result | Add-Member -NotePropertyName KeepAChangelogVersion -NotePropertyValue (Get-KeepAChangelogModuleVersion) -Force
        $targetVersion = $result.Release.Version

        if (-not $PSCmdlet.ShouldProcess($Path, "Promote [Unreleased] to [$targetVersion]")) {
            return $result
        }

        Set-Content -LiteralPath $Path -Value $result.UpdatedText -Encoding utf8 -NoNewline
        return $result
    }
}


# Source: src/public/Test-KeepAChangelogFile.ps1
function Test-KeepAChangelogFile {
    [CmdletBinding()]
    param(
        [Parameter(Position = 0)]
        [string]$Path = 'CHANGELOG.md',

        [switch]$ThrowOnError
    )

    if (-not (Test-Path -LiteralPath $Path)) {
        throw "Could not find CHANGELOG file at '$Path'."
    }

    $text = Get-Content -LiteralPath $Path -Raw
    $result = Get-KeepAChangelogValidationResult -Text $text
    $result | Add-Member -NotePropertyName Path -NotePropertyValue $Path -Force

    if ($ThrowOnError -and -not $result.IsValid) {
        throw ($result.Errors -join ' ')
    }

    return $result
}


# Source: src/private/initialize/Assert-KeepAChangelogInitialization.ps1
function Assert-KeepAChangelogInitialization {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Path,
        [Parameter(Mandatory)]
        [string]$RepositoryUrl,
        [Parameter(Mandatory)]
        [bool]$Force
    )

    if ([string]::IsNullOrWhiteSpace($RepositoryUrl)) {
        throw 'RepositoryUrl is required.'
    }

    if ((Test-Path -LiteralPath $Path) -and -not $Force) {
        throw "File already exists at '$Path'. Use -Force to overwrite it."
    }
}


# Source: src/private/initialize/Get-KeepAChangelogFooterLine.ps1
function Get-KeepAChangelogFooterLine {
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$RepositoryState,

        [string]$PreviousReleaseReference
    )

    if ([string]::IsNullOrWhiteSpace($PreviousReleaseReference)) {
        return $null
    }

    $repositoryLinkData = Get-KeepAChangelogRepositoryLinkData -RepositoryState $RepositoryState
    $compareLink = Get-KeepAChangelogCompareLink `
        -RepositoryLinkData $repositoryLinkData `
        -BaseReference $PreviousReleaseReference `
        -TargetReference $repositoryLinkData.UnreleasedTargetReference

    return "[Unreleased]: $compareLink"
}


# Source: src/private/initialize/Get-KeepAChangelogHeadingLineList.ps1
function Get-KeepAChangelogHeadingLineList {
    [CmdletBinding()]
    [OutputType([object[]])]
    param(
        [Parameter(Mandatory)]
        [string[]]$SectionHeading
    )

    return @(
        foreach ($heading in $SectionHeading) {
            "### $heading"
            ''
        }
    )
}


# Source: src/private/initialize/Get-KeepAChangelogTemplateText.ps1
function Get-KeepAChangelogTemplateText {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$RepositoryState,

        [string]$PreviousReleaseReference,

        [Parameter(Mandatory)]
        [string[]]$SectionHeading
    )

    $footerLine = Get-KeepAChangelogFooterLine `
        -RepositoryState $RepositoryState `
        -PreviousReleaseReference $PreviousReleaseReference
    $lineList = @(
        '# Changelog'
        ''
        'All notable changes to this project will be documented in this file.'
        ''
        'The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),'
        'and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).'
        ''
        '## [Unreleased]'
        ''
        (Get-KeepAChangelogHeadingLineList -SectionHeading $SectionHeading)
        $footerLine
    ) | Where-Object { $null -ne $_ }

    return (($lineList -join "`n").TrimEnd() + "`n")
}


# Source: src/private/release/Add-ChangelogTagMessageBlankLine.ps1
function Add-ChangelogTagMessageBlankLine {
    [CmdletBinding()]
    [OutputType([bool])]
    param(
        [Parameter(Mandatory)]
        [object]$LineList,
        [Parameter(Mandatory)]
        [bool]$AllowBlankLine
    )

    if (-not $AllowBlankLine -or $LineList.Count -eq 0) {
        return $false
    }

    $LineList.Add('')
    return $false
}


# Source: src/private/release/Assert-KeepAChangelogRelease.ps1
function Assert-KeepAChangelogRelease {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [hashtable]$Release
    )

    $requiredKeyList = @('Version', 'Date', 'Tag')

    foreach ($requiredKey in $requiredKeyList) {
        if (-not $Release.ContainsKey($requiredKey)) {
            throw "Release.$requiredKey is required."
        }

        if ([string]::IsNullOrWhiteSpace([string]$Release[$requiredKey])) {
            throw "Release.$requiredKey is required."
        }
    }

    return [pscustomobject]@{
        Version   = [string]$Release.Version
        Date      = [string]$Release.Date
        Tag       = [string]$Release.Tag
        Reference = if (-not $Release.ContainsKey('Reference') -or [string]::IsNullOrWhiteSpace([string]$Release['Reference'])) { [string]$Release.Tag } else { [string]$Release['Reference'] }
    }
}


# Source: src/private/release/Assert-KeepAChangelogReleaseDateOrder.ps1
function Get-KeepAChangelogLatestReleaseDate {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Body
    )

    $latestReleaseDate = $null
    foreach ($match in [regex]::Matches($Body, '(?m)^## \[[^\]]+\] - (?<date>\d{4}-\d{2}-\d{2})$')) {
        $releaseDate = [datetime]::ParseExact(
            $match.Groups['date'].Value,
            'yyyy-MM-dd',
            [System.Globalization.CultureInfo]::InvariantCulture
        )

        if ($null -eq $latestReleaseDate -or $releaseDate -gt $latestReleaseDate) {
            $latestReleaseDate = $releaseDate
        }
    }

    if ($null -eq $latestReleaseDate) {
        return $null
    }

    return $latestReleaseDate.ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture)
}

function Assert-KeepAChangelogReleaseDateOrder {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Body,
        [Parameter(Mandatory)]
        [pscustomobject]$Release
    )

    $latestExistingReleaseDate = Get-KeepAChangelogLatestReleaseDate -Body $Body
    if ([string]::IsNullOrWhiteSpace($latestExistingReleaseDate)) {
        return
    }

    $releaseDate = [datetime]::ParseExact(
        $Release.Date,
        'yyyy-MM-dd',
        [System.Globalization.CultureInfo]::InvariantCulture
    )
    $latestReleaseDate = [datetime]::ParseExact(
        $latestExistingReleaseDate,
        'yyyy-MM-dd',
        [System.Globalization.CultureInfo]::InvariantCulture
    )

    if ($releaseDate -lt $latestReleaseDate) {
        throw "Release.Date '$($Release.Date)' cannot be earlier than latest existing release date '$latestExistingReleaseDate'."
    }
}


# Source: src/private/release/Get-ChangelogReleaseNotesBody.ps1
function Get-ChangelogReleaseNotesBody {
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyString()]
        [string]$Body
    )

    $trimmedBody = $Body.Trim()

    if ([string]::IsNullOrWhiteSpace($trimmedBody)) {
        return ''
    }

    if ($trimmedBody -notmatch '(?m)^[ \t]*###\s+') {
        return $trimmedBody
    }

    $sectionPattern = '(?ms)^(?<heading>[ \t]*###\s+[^\r\n]+)\r?\n(?<content>.*?)(?=^[ \t]*###\s+|\z)'
    $sectionMatchList = [regex]::Matches($trimmedBody, $sectionPattern)
    $sectionTextList = [System.Collections.Generic.List[string]]::new()

    foreach ($sectionMatch in $sectionMatchList) {
        $heading = $sectionMatch.Groups['heading'].Value.TrimEnd()
        $content = $sectionMatch.Groups['content'].Value.Trim()

        if ([string]::IsNullOrWhiteSpace($content)) {
            continue
        }

        $sectionTextList.Add("$heading`n`n$content")
    }

    return ($sectionTextList -join "`n`n").Trim()
}


# Source: src/private/release/Get-ChangelogTagMessageLine.ps1
function Get-ChangelogTagMessageLine {
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [string]$TrimmedLine
    )

    if ($TrimmedLine -match '^###\s+(?<value>.+)$') {
        return $Matches.value
    }

    if ($TrimmedLine -match '^(?:-|\*)\s+(?<value>.+)$') {
        return $Matches.value
    }

    return $TrimmedLine
}


# Source: src/private/release/Get-ClearedUnreleasedBody.ps1
function Get-ClearedUnreleasedBody {
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyString()]
        [string]$Body
    )

    $headingList = @(
        [regex]::Matches($Body, '(?m)^[ \t]*###\s+[^\r\n]+') |
            ForEach-Object { $_.Value.TrimEnd() }
    )

    if (-not $headingList) {
        return ''
    }

    return ($headingList -join "`n`n").TrimEnd()
}


# Source: src/private/release/Get-KeepAChangelogPreviousReleaseReference.ps1
function Get-ChangelogReleaseTargetReference {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Link
    )

    $compareMatch = [regex]::Match($Link, '/(?:compare|-/compare)/.+\.\.\.(?<target>.+)$')
    if ($compareMatch.Success) {
        return $compareMatch.Groups['target'].Value
    }

    $azureCompareMatch = [regex]::Match(
        $Link,
        'branchCompare\?baseVersion=.+?(?:&|&amp;)targetVersion=(?<target>.+?)(?:&|&amp;)_a=commits$'
    )
    if ($azureCompareMatch.Success) {
        return $azureCompareMatch.Groups['target'].Value
    }

    $tagMatch = [regex]::Match($Link, '/(?:releases/tag|-/tags)/(?<target>.+)$')
    if ($tagMatch.Success) {
        return $tagMatch.Groups['target'].Value
    }

    return $null
}

function Get-KeepAChangelogPreviousReleaseReference {
    [CmdletBinding()]
    param(
        [AllowEmptyString()]
        [string]$Footer,
        [Parameter(Mandatory)]
        [pscustomobject]$Validation,
        [Parameter(Mandatory)]
        [pscustomobject]$Release
    )

    $previousReleaseReference = $Validation.PreviousReleaseReference
    if ([string]::IsNullOrWhiteSpace($previousReleaseReference)) {
        return $null
    }

    if ($previousReleaseReference -ne $Release.Reference) {
        return $previousReleaseReference
    }

    $referenceLinkData = Get-ChangelogReferenceLinkData -Footer $Footer
    foreach ($releaseVersion in $Validation.ReleaseVersions) {
        if (-not $referenceLinkData.LinkMap.Contains($releaseVersion)) {
            continue
        }

        $releaseTargetReference = Get-ChangelogReleaseTargetReference -Link $referenceLinkData.LinkMap[$releaseVersion]
        if (-not [string]::IsNullOrWhiteSpace($releaseTargetReference) -and $releaseTargetReference -ne $Release.Reference) {
            return $releaseTargetReference
        }
    }

    return $null
}


# Source: src/private/release/Get-TrimmedChangelogTagMessageLineList.ps1
function Get-TrimmedChangelogTagMessageLineList {
    [CmdletBinding()]
    [OutputType([System.Collections.Generic.List[System.String]])]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [AllowEmptyString()]
        [System.Collections.Generic.List[string]]$LineList
    )

    $trimmedLineList = [System.Collections.Generic.List[string]]::new()
    foreach ($line in $LineList) {
        $trimmedLineList.Add($line)
    }

    while ($trimmedLineList.Count -gt 0 -and [string]::IsNullOrWhiteSpace($trimmedLineList[$trimmedLineList.Count - 1])) {
        $trimmedLineList.RemoveAt($trimmedLineList.Count - 1)
    }

    return $trimmedLineList
}


# Source: src/private/release/Get-UnreleasedSectionMatch.ps1
function Get-UnreleasedSectionMatch {
    [CmdletBinding()]
    [OutputType([System.Text.RegularExpressions.Match])]
    param(
        [Parameter(Mandatory)]
        [string]$Text
    )

    $pattern = '(?ms)^##\s+\[Unreleased\]\s*\r?\n(?<body>.*?)(?=^##\s+\[|\z)'
    $match = [regex]::Match($Text, $pattern)

    if (-not $match.Success) {
        throw 'Could not find ## [Unreleased] section in CHANGELOG.md.'
    }

    return $match
}


# Source: src/private/release/Get-UpdatedChangelogReferenceFooter.ps1
function Get-ChangelogReferenceLinkData {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyString()]
        [string]$Footer
    )

    $orderedLabelList = [System.Collections.Generic.List[string]]::new()
    $linkMap = [ordered]@{}

    foreach ($referenceMatch in [regex]::Matches($Footer, '(?m)^\[(?<label>[^\]]+)\]:\s*(?<url>\S.*?)\s*$')) {
        $label = $referenceMatch.Groups['label'].Value
        $url = $referenceMatch.Groups['url'].Value.Trim()

        if (-not $linkMap.Contains($label)) {
            $orderedLabelList.Add($label)
        }

        $linkMap[$label] = $url
    }

    return [pscustomobject]@{
        OrderedLabelList = $orderedLabelList
        LinkMap          = $linkMap
    }
}

function Get-ChangelogReleaseLink {
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Context,
        [AllowEmptyString()]
        [string]$PreviousReleaseReference,
        [Parameter(Mandatory)]
        [string]$ReleaseReference
    )

    if ([string]::IsNullOrWhiteSpace($PreviousReleaseReference)) {
        if (-not [string]::IsNullOrWhiteSpace($Context.ReleaseTagPrefix)) {
            return "$($Context.ReleaseTagPrefix)$ReleaseReference"
        }

        return Get-KeepAChangelogCompareLink `
            -RepositoryLinkData $Context `
            -BaseReference $ReleaseReference `
            -TargetReference $ReleaseReference
    }

    return Get-KeepAChangelogCompareLink `
        -RepositoryLinkData $Context `
        -BaseReference $PreviousReleaseReference `
        -TargetReference $ReleaseReference
}

function Add-ChangelogReferenceLabel {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Collections.Generic.List[string]]$OrderedLabelList,
        [Parameter(Mandatory)]
        [hashtable]$LinkMap,
        [Parameter(Mandatory)]
        [string]$Label
    )

    if ($LinkMap.Contains($Label)) {
        return
    }

    $OrderedLabelList.Insert($OrderedLabelList.IndexOf('Unreleased') + 1, $Label)
}

function Get-UpdatedChangelogReferenceFooter {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyString()]
        [string]$Footer,

        [Parameter(Mandatory)]
        [pscustomobject]$Release,

        [Parameter(Mandatory)]
        [pscustomobject]$Context
    )

    $shouldWriteReferenceFooter = $true
    if ($Context.PSObject.Properties.Name -contains 'ShouldWriteReferenceFooter') {
        $shouldWriteReferenceFooter = [bool]$Context.ShouldWriteReferenceFooter
    }

    if (-not $shouldWriteReferenceFooter) {
        return [pscustomobject]@{
            Footer               = ''
            UpdatedUnreleasedLink = $null
            NewReleaseCompareLink = $null
            NewReleaseLink        = $null
        }
    }

    $referenceLinkData = Get-ChangelogReferenceLinkData -Footer $Footer
    $orderedLabelList = $referenceLinkData.OrderedLabelList
    $linkMap = $referenceLinkData.LinkMap

    if (-not $linkMap.Contains('Unreleased')) {
        $orderedLabelList.Add('Unreleased')
    }

    $updatedUnreleasedLink = Get-KeepAChangelogCompareLink `
        -RepositoryLinkData $Context `
        -BaseReference $Release.Reference `
        -TargetReference $Context.UnreleasedTargetReference
    $newReleaseLink = Get-ChangelogReleaseLink `
        -Context $Context `
        -PreviousReleaseReference $Context.PreviousReleaseReference `
        -ReleaseReference $Release.Reference
    $linkMap['Unreleased'] = $updatedUnreleasedLink

    Add-ChangelogReferenceLabel -OrderedLabelList $orderedLabelList -LinkMap $linkMap -Label $Release.Version
    $linkMap[$Release.Version] = $newReleaseLink

    $footerLineList = foreach ($label in $orderedLabelList) {
        "[$label]: $($linkMap[$label])"
    }

    return [pscustomobject]@{
        Footer               = ($footerLineList -join "`n").TrimEnd()
        UpdatedUnreleasedLink = $updatedUnreleasedLink
        NewReleaseCompareLink = $newReleaseLink
        NewReleaseLink        = $newReleaseLink
    }
}


# Source: src/private/release/Resolve-KeepAChangelogReleaseData.ps1
function Get-KeepAChangelogRepositoryState {
    [CmdletBinding()]
    param(
        [string]$RepositoryUrl,
        [string]$RepositoryProvider,
        [string]$RepositoryTargetReference,
        [AllowEmptyString()]
        [string]$Footer
    )

    return [pscustomobject]@{
        Footer                    = $Footer
        RepositoryProvider        = $RepositoryProvider
        RepositoryTargetReference = $RepositoryTargetReference
        RepositoryUrl             = $RepositoryUrl
    }
}

function Assert-KeepAChangelogValidation {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Validation
    )

    if (-not $Validation.IsValid) {
        throw "CHANGELOG.md is not valid. $($Validation.Errors -join ' ')"
    }
}

function Get-KeepAChangelogRepositoryContext {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$RepositoryState,
        [Parameter(Mandatory)]
        [pscustomobject]$Release,
        [Parameter(Mandatory)]
        [pscustomobject]$Validation
    )

    $normalizedRepositoryUrl = if ([string]::IsNullOrWhiteSpace($RepositoryState.RepositoryUrl)) {
        $null
    }
    else {
        $RepositoryState.RepositoryUrl.TrimEnd('/')
    }

    $unreleasedCompareLinkPrefix = $Validation.UnreleasedCompareLinkPrefix
    $shouldWriteReferenceFooter = (-not [string]::IsNullOrWhiteSpace($unreleasedCompareLinkPrefix)) -or `
        (-not [string]::IsNullOrWhiteSpace($normalizedRepositoryUrl))

    if (-not $shouldWriteReferenceFooter) {
        return [pscustomobject]@{
            RepositoryUrl               = $null
            UnreleasedCompareLinkPrefix = $null
            UnreleasedTargetReference   = $null
            CompareLinkPrefix           = $null
            CompareLinkSeparator        = $null
            CompareLinkSuffix           = $null
            ReleaseTagPrefix            = $null
            PreviousReleaseReference    = $null
            ShouldWriteReferenceFooter  = $false
        }
    }

    $repositoryLinkData = Get-KeepAChangelogRepositoryLinkData -RepositoryState ([pscustomobject]@{
            RepositoryUrl             = $normalizedRepositoryUrl
            RepositoryProvider        = $RepositoryState.RepositoryProvider
            RepositoryTargetReference = $RepositoryState.RepositoryTargetReference
            UnreleasedCompareLinkPrefix = $unreleasedCompareLinkPrefix
            UnreleasedTargetReference = $Validation.UnreleasedTargetReference
        })

    $previousReleaseReference = Get-KeepAChangelogPreviousReleaseReference `
        -Footer $RepositoryState.Footer `
        -Validation $Validation `
        -Release $Release

    return [pscustomobject]@{
        RepositoryProvider          = $repositoryLinkData.RepositoryProvider
        RepositoryUrl               = $repositoryLinkData.RepositoryUrl
        UnreleasedCompareLinkPrefix = $repositoryLinkData.UnreleasedCompareLinkPrefix
        UnreleasedTargetReference   = $repositoryLinkData.UnreleasedTargetReference
        CompareLinkSeparator        = $repositoryLinkData.CompareLinkSeparator
        CompareLinkSuffix           = $repositoryLinkData.CompareLinkSuffix
        ReleaseTagPrefix            = $repositoryLinkData.ReleaseTagPrefix
        PreviousReleaseReference    = $previousReleaseReference
        ShouldWriteReferenceFooter  = $true
    }
}

function Get-KeepAChangelogSectionText {
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [string]$Heading,
        [AllowEmptyString()]
        [string]$Body
    )

    if ([string]::IsNullOrWhiteSpace($Body)) {
        return $Heading
    }

    return "$Heading`n`n$Body"
}

function Get-UpdatedChangelogBodyText {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Parts,
        [Parameter(Mandatory)]
        [System.Text.RegularExpressions.Match]$UnreleasedSectionMatch,
        [Parameter(Mandatory)]
        [string]$UnreleasedSection,
        [Parameter(Mandatory)]
        [string]$ReleaseSection
    )

    $beforeUnreleased = $Parts.Body.Substring(0, $UnreleasedSectionMatch.Index).TrimEnd()
    $afterUnreleasedStart = $UnreleasedSectionMatch.Index + $UnreleasedSectionMatch.Length
    $afterUnreleased = $Parts.Body.Substring($afterUnreleasedStart).TrimStart("`r", "`n")

    return (@(
            $beforeUnreleased
            $UnreleasedSection
            $ReleaseSection
            $afterUnreleased
        ) |
        Where-Object {-not [string]::IsNullOrWhiteSpace($_)} |
        ForEach-Object {$_.TrimEnd()} |
        Join-String -Separator "`n`n").TrimEnd()
}

function Resolve-KeepAChangelogReleaseData {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Text,

        [Parameter(Mandatory)]
        [hashtable]$Release,

        [pscustomobject]$RepositoryState
    )

    $normalizedRelease = Assert-KeepAChangelogRelease -Release $Release
    $validation = Get-KeepAChangelogValidationResult -Text $Text
    Assert-KeepAChangelogValidation -Validation $validation
    $parts = Split-KeepAChangelogText -Text $Text
    Assert-KeepAChangelogReleaseDateOrder -Body $parts.Body -Release $normalizedRelease
    $unreleasedSectionMatch = Get-UnreleasedSectionMatch -Text $parts.Body
    $repositoryState = Get-KeepAChangelogRepositoryState `
        -RepositoryUrl $RepositoryState.RepositoryUrl `
        -RepositoryProvider $RepositoryState.RepositoryProvider `
        -RepositoryTargetReference $RepositoryState.RepositoryTargetReference `
        -Footer $parts.Footer
    $repositoryContext = Get-KeepAChangelogRepositoryContext `
        -RepositoryState $repositoryState `
        -Release $normalizedRelease `
        -Validation $validation
    $unreleasedBody = $unreleasedSectionMatch.Groups['body'].Value.Trim()
    $releaseNotesBody = Get-ChangelogReleaseNotesBody -Body $unreleasedBody
    $clearedUnreleasedBody = Get-ClearedUnreleasedBody -Body $unreleasedBody
    $unreleasedSection = Get-KeepAChangelogSectionText -Heading '## [Unreleased]' -Body $clearedUnreleasedBody
    $newReleaseSection = Get-KeepAChangelogSectionText -Heading "## [$($normalizedRelease.Version)] - $($normalizedRelease.Date)" -Body $releaseNotesBody
    $updatedBody = Get-UpdatedChangelogBodyText `
        -Parts $parts `
        -UnreleasedSectionMatch $unreleasedSectionMatch `
        -UnreleasedSection $unreleasedSection `
        -ReleaseSection $newReleaseSection
    $updatedFooterData = Get-UpdatedChangelogReferenceFooter `
        -Footer $parts.Footer `
        -Release $normalizedRelease `
        -Context $repositoryContext
    $updatedText = @(
        $updatedBody
        $updatedFooterData.Footer
    ) |
        Where-Object { -not [string]::IsNullOrWhiteSpace($_) } |
        ForEach-Object { $_.TrimEnd() } |
        Join-String -Separator "`n`n"
    $updatedText = $updatedText.TrimEnd() + "`n"

    return [pscustomobject]@{
        Release                     = $normalizedRelease
        UnreleasedCompareLinkPrefix = $repositoryContext.UnreleasedCompareLinkPrefix
        PreviousReleaseReference    = $repositoryContext.PreviousReleaseReference
        UnreleasedBody              = $unreleasedBody
        ReleaseNotesBody            = $releaseNotesBody
        ClearedUnreleasedBody       = $clearedUnreleasedBody
        NewReleaseSection           = $newReleaseSection
        UpdatedUnreleasedLink       = $updatedFooterData.UpdatedUnreleasedLink
        NewReleaseCompareLink       = $updatedFooterData.NewReleaseCompareLink
        NewReleaseLink              = $updatedFooterData.NewReleaseLink
        TagMessageText              = Convert-ChangelogReleaseNotesToTagMessage -ReleaseNotes $releaseNotesBody
        UpdatedText                 = $updatedText
    }
}


# Source: src/private/release/Resolve-KeepAChangelogReleaseDate.ps1
function Resolve-KeepAChangelogReleaseDate {
    [CmdletBinding()]
    param(
        [AllowEmptyString()]
        [string]$Date
    )

    if ([string]::IsNullOrWhiteSpace($Date)) {
        return (Get-Date).ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture)
    }

    $parsedDate = [datetime]::MinValue
    $isValidDate = [datetime]::TryParseExact(
        $Date,
        'yyyy-MM-dd',
        [System.Globalization.CultureInfo]::InvariantCulture,
        [System.Globalization.DateTimeStyles]::None,
        [ref]$parsedDate
    )

    if (-not $isValidDate) {
        throw "Date must use yyyy-MM-dd format. Received: '$Date'."
    }

    return $parsedDate.ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture)
}


# Source: src/private/shared/Get-KeepAChangelogModuleVersion.ps1
function Read-KeepAChangelogProjectVersion {
    [CmdletBinding()]
    [OutputType([string])]
    param()

    $projectJsonPath = [System.IO.Path]::GetFullPath((Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '..', '..', 'project.json'))
    $project = Get-Content -LiteralPath $projectJsonPath -Raw | ConvertFrom-Json
    return [string]$project.Version
}

function Get-KeepAChangelogLoadedModuleVersion {
    [CmdletBinding()]
    param()

    $module = $ExecutionContext.SessionState.Module
    if ($null -eq $module) {
        return $null
    }

    if ($module.Name -ne 'KeepAChangelog') {
        return $null
    }

    if ($null -eq $module.Version) {
        return $null
    }

    return $module.Version.ToString()
}

function Get-KeepAChangelogModuleVersion {
    [CmdletBinding()]
    param()

    $loadedModuleVersion = Get-KeepAChangelogLoadedModuleVersion
    if (-not [string]::IsNullOrWhiteSpace($loadedModuleVersion)) {
        return $loadedModuleVersion
    }

    return Read-KeepAChangelogProjectVersion
}


# Source: src/private/shared/Get-KeepAChangelogRepositoryLinkData.ps1
function Test-KeepAChangelogRepositoryUrlMatch {
    param(
        [Parameter(Mandatory = $true)]
        [AllowEmptyString()]
        [string]$RepositoryUrl,

        [Parameter(Mandatory = $true)]
        [string]$Pattern
    )

    if ([string]::IsNullOrWhiteSpace($RepositoryUrl)) {
        return $false
    }

    return $RepositoryUrl -match $Pattern
}

function Test-KeepAChangelogGitLabRepositoryUrl {
    param(
        [Parameter(Mandatory = $true)]
        [AllowEmptyString()]
        [string]$RepositoryUrl
    )

    return Test-KeepAChangelogRepositoryUrlMatch -RepositoryUrl $RepositoryUrl -Pattern 'https?://[^/]*gitlab[^/]*/'
}

function Test-KeepAChangelogAzureDevOpsRepositoryUrl {
    param(
        [Parameter(Mandatory = $true)]
        [AllowEmptyString()]
        [string]$RepositoryUrl
    )

    return Test-KeepAChangelogRepositoryUrlMatch -RepositoryUrl $RepositoryUrl -Pattern '/_git/'
}

function Get-KeepAChangelogRepositoryProviderSetting {
    param(
        [Parameter(Mandatory = $true)]
        [ValidateSet('GitHub', 'GitLab', 'AzureDevOps')]
        [string]$RepositoryProvider
    )

    $settingsByProvider = @{
        GitHub = [pscustomobject]@{
            CompareLinkPrefixSegment      = '/compare/'
            CompareLinkSeparator          = '...'
            CompareLinkSuffix             = ''
            DefaultUnreleasedTargetReference = 'HEAD'
            ReleaseTagPath                = '/releases/tag/'
        }
        GitLab = [pscustomobject]@{
            CompareLinkPrefixSegment      = '/-/compare/'
            CompareLinkSeparator          = '...'
            CompareLinkSuffix             = ''
            DefaultUnreleasedTargetReference = 'HEAD'
            ReleaseTagPath                = '/-/tags/'
        }
        AzureDevOps = [pscustomobject]@{
            CompareLinkPrefixSegment      = '/branchCompare?baseVersion='
            CompareLinkSeparator          = '&targetVersion='
            CompareLinkSuffix             = '&_a=commits'
            DefaultUnreleasedTargetReference = $null
            ReleaseTagPath                = $null
        }
    }

    return $settingsByProvider[$RepositoryProvider]
}

function Get-KeepAChangelogRepositoryProviderFromComparePrefix {
    param(
        [AllowNull()]
        [AllowEmptyString()]
        [string]$UnreleasedCompareLinkPrefix
    )

    if ([string]::IsNullOrWhiteSpace($UnreleasedCompareLinkPrefix)) {
        return $null
    }

    if ($UnreleasedCompareLinkPrefix -like '*/branchCompare?baseVersion=*') {
        return 'AzureDevOps'
    }

    if ($UnreleasedCompareLinkPrefix -like '*-/compare/*') {
        return 'GitLab'
    }

    return 'GitHub'
}

function Get-KeepAChangelogRepositoryProviderFromUrl {
    param(
        [AllowNull()]
        [AllowEmptyString()]
        [string]$RepositoryUrl
    )

    if (Test-KeepAChangelogAzureDevOpsRepositoryUrl -RepositoryUrl $RepositoryUrl) {
        return 'AzureDevOps'
    }

    if (Test-KeepAChangelogGitLabRepositoryUrl -RepositoryUrl $RepositoryUrl) {
        return 'GitLab'
    }

    return 'GitHub'
}

function Get-KeepAChangelogRepositoryProvider {
    param(
        [AllowNull()]
        [AllowEmptyString()]
        [string]$RepositoryUrl,

        [AllowNull()]
        [AllowEmptyString()]
        [string]$RepositoryProvider,

        [AllowNull()]
        [AllowEmptyString()]
        [string]$UnreleasedCompareLinkPrefix
    )

    $detectedProvider = Get-KeepAChangelogRepositoryProviderFromComparePrefix -UnreleasedCompareLinkPrefix $UnreleasedCompareLinkPrefix
    if ($null -ne $detectedProvider) {
        return $detectedProvider
    }

    if (-not [string]::IsNullOrWhiteSpace($RepositoryProvider)) {
        return $RepositoryProvider
    }

    return Get-KeepAChangelogRepositoryProviderFromUrl -RepositoryUrl $RepositoryUrl
}

function Get-KeepAChangelogUnreleasedTargetReference {
    param(
        [Parameter(Mandatory = $true)]
        [ValidateSet('GitHub', 'GitLab', 'AzureDevOps')]
        [string]$RepositoryProvider,

        [AllowNull()]
        [AllowEmptyString()]
        [string]$RepositoryTargetReference,

        [AllowNull()]
        [AllowEmptyString()]
        [string]$UnreleasedTargetReference
    )

    if (-not [string]::IsNullOrWhiteSpace($UnreleasedTargetReference)) {
        return $UnreleasedTargetReference
    }

    if (-not [string]::IsNullOrWhiteSpace($RepositoryTargetReference)) {
        return $RepositoryTargetReference
    }

    return (Get-KeepAChangelogRepositoryProviderSetting -RepositoryProvider $RepositoryProvider).DefaultUnreleasedTargetReference
}

function Resolve-KeepAChangelogRepositoryUrlFromComparePrefix {
    param(
        [Parameter(Mandatory = $true)]
        [string]$UnreleasedCompareLinkPrefix,

        [Parameter(Mandatory = $true)]
        [ValidateSet('GitHub', 'GitLab', 'AzureDevOps')]
        [string]$RepositoryProvider
    )

    $compareLinkPrefixSegment = (Get-KeepAChangelogRepositoryProviderSetting -RepositoryProvider $RepositoryProvider).CompareLinkPrefixSegment
    return $UnreleasedCompareLinkPrefix.Substring(0, $UnreleasedCompareLinkPrefix.Length - $compareLinkPrefixSegment.Length)
}

function Get-KeepAChangelogCompareLink {
    param(
        [Parameter(Mandatory = $true)]
        [pscustomobject]$RepositoryLinkData,

        [Parameter(Mandatory = $true)]
        [string]$BaseReference,

        [Parameter(Mandatory = $true)]
        [string]$TargetReference
    )

    return '{0}{1}{2}{3}{4}' -f `
        $RepositoryLinkData.UnreleasedCompareLinkPrefix, `
        $BaseReference, `
        $RepositoryLinkData.CompareLinkSeparator, `
        $TargetReference, `
        $RepositoryLinkData.CompareLinkSuffix
}

function Get-KeepAChangelogRepositoryLinkData {
    param(
        [Parameter(Mandatory = $true)]
        [pscustomobject]$RepositoryState
    )

    $repositoryUrl = $RepositoryState.RepositoryUrl
    $repositoryProvider = $RepositoryState.RepositoryProvider
    $repositoryTargetReference = $RepositoryState.RepositoryTargetReference
    $unreleasedCompareLinkPrefix = $RepositoryState.UnreleasedCompareLinkPrefix
    $unreleasedTargetReference = $RepositoryState.UnreleasedTargetReference

    if ([string]::IsNullOrWhiteSpace($repositoryUrl) -and [string]::IsNullOrWhiteSpace($unreleasedCompareLinkPrefix)) {
        return $null
    }

    $resolvedProvider = Get-KeepAChangelogRepositoryProvider `
        -RepositoryUrl $repositoryUrl `
        -RepositoryProvider $repositoryProvider `
        -UnreleasedCompareLinkPrefix $unreleasedCompareLinkPrefix
    $providerSettings = Get-KeepAChangelogRepositoryProviderSetting -RepositoryProvider $resolvedProvider

    if ([string]::IsNullOrWhiteSpace($repositoryUrl)) {
        $repositoryUrl = Resolve-KeepAChangelogRepositoryUrlFromComparePrefix `
            -UnreleasedCompareLinkPrefix $unreleasedCompareLinkPrefix `
            -RepositoryProvider $resolvedProvider
    }

    if ([string]::IsNullOrWhiteSpace($unreleasedCompareLinkPrefix)) {
        $unreleasedCompareLinkPrefix = '{0}{1}' -f $repositoryUrl, $providerSettings.CompareLinkPrefixSegment
    }

    $resolvedTargetReference = Get-KeepAChangelogUnreleasedTargetReference `
        -RepositoryProvider $resolvedProvider `
        -RepositoryTargetReference $repositoryTargetReference `
        -UnreleasedTargetReference $unreleasedTargetReference

    if (($resolvedProvider -eq 'AzureDevOps') -and [string]::IsNullOrWhiteSpace($resolvedTargetReference)) {
        throw 'RepositoryTargetReference is required when AzureDevOps footer links must be generated.'
    }

    $releaseTagPrefix = $null
    if ($null -ne $providerSettings.ReleaseTagPath) {
        $releaseTagPrefix = '{0}{1}' -f $repositoryUrl, $providerSettings.ReleaseTagPath
    }

    return [pscustomobject]@{
        RepositoryUrl            = $repositoryUrl
        RepositoryProvider       = $resolvedProvider
        UnreleasedCompareLinkPrefix = $unreleasedCompareLinkPrefix
        CompareLinkSeparator     = $providerSettings.CompareLinkSeparator
        CompareLinkSuffix        = $providerSettings.CompareLinkSuffix
        UnreleasedTargetReference = $resolvedTargetReference
        ReleaseTagPrefix         = $releaseTagPrefix
    }
}


# Source: src/private/shared/Get-KeepAChangelogRepositoryProviderParameterDictionary.ps1
function Get-KeepAChangelogRuntimeDefinedParameter {
    [CmdletBinding()]
    [OutputType([System.Management.Automation.RuntimeDefinedParameter])]
    param(
        [Parameter(Mandatory)]
        [string]$Name,
        [Parameter(Mandatory)]
        [type]$ParameterType,
        [string[]]$ValidateSetValue
    )

    $attribute = [System.Management.Automation.ParameterAttribute]::new()
    $attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
    $attributeCollection.Add($attribute)

    if ($null -ne $ValidateSetValue -and $ValidateSetValue.Count -gt 0) {
        $attributeCollection.Add([System.Management.Automation.ValidateSetAttribute]::new($ValidateSetValue))
    }

    return [System.Management.Automation.RuntimeDefinedParameter]::new(
        $Name,
        $ParameterType,
        $attributeCollection
    )
}

function Get-KeepAChangelogRepositoryProviderParameterDictionary {
    [CmdletBinding()]
    [OutputType([System.Management.Automation.RuntimeDefinedParameterDictionary])]
    param(
        [switch]$IncludeReleaseReference,
        [switch]$IncludeRepositoryTargetReference
    )

    $parameterDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
    $parameterDictionary.Add(
        'RepositoryProvider',
        (Get-KeepAChangelogRuntimeDefinedParameter `
            -Name 'RepositoryProvider' `
            -ParameterType ([string]) `
            -ValidateSetValue @('GitHub', 'GitLab', 'AzureDevOps'))
    )

    if ($IncludeRepositoryTargetReference) {
        $parameterDictionary.Add(
            'RepositoryTargetReference',
            (Get-KeepAChangelogRuntimeDefinedParameter -Name 'RepositoryTargetReference' -ParameterType ([string]))
        )
    }

    if ($IncludeReleaseReference) {
        $parameterDictionary.Add(
            'ReleaseReference',
            (Get-KeepAChangelogRuntimeDefinedParameter -Name 'ReleaseReference' -ParameterType ([string]))
        )
    }

    return $parameterDictionary
}


# Source: src/private/shared/Split-KeepAChangelogText.ps1
function Split-KeepAChangelogText {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Text
    )

    $footerPattern = '(?ms)(?<footer>(?:^\[[^\]]+\]:[^\r\n]*(?:\r?\n(?:[ \t]*\r?\n)*)?)+)\s*\z'
    $footerMatch = [regex]::Match($Text, $footerPattern)

    if ($footerMatch.Success) {
        return [pscustomobject]@{
            Body   = $Text.Substring(0, $footerMatch.Index).TrimEnd()
            Footer = $footerMatch.Groups['footer'].Value.TrimEnd()
        }
    }

    return [pscustomobject]@{
        Body   = $Text.TrimEnd()
        Footer = ''
    }
}


# Source: src/private/validation/Add-KeepAChangelogDuplicateReferenceLinkError.ps1
function Add-KeepAChangelogDuplicateReferenceLinkError {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [hashtable]$ReferenceLabelCountMap,
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [System.Collections.Generic.List[string]]$ErrorList
    )

    foreach ($label in $ReferenceLabelCountMap.Keys) {
        if ($ReferenceLabelCountMap[$label] -le 1) {
            continue
        }

        $ErrorList.Add("Reference link [$label] is duplicated.")
    }
}


# Source: src/private/validation/Get-KeepAChangelogReferenceLabelCountMap.ps1
function Get-KeepAChangelogReferenceLabelCountMap {
    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [AllowEmptyString()]
        [string]$Footer
    )

    $referenceLabelCountMap = @{}
    if ([string]::IsNullOrWhiteSpace($Footer)) {
        return $referenceLabelCountMap
    }

    foreach ($referenceMatch in [regex]::Matches($Footer, '(?m)^\[(?<label>[^\]]+)\]:')) {
        $label = $referenceMatch.Groups['label'].Value
        if (-not $referenceLabelCountMap.ContainsKey($label)) {
            $referenceLabelCountMap[$label] = 0
        }

        $referenceLabelCountMap[$label]++
    }

    return $referenceLabelCountMap
}


# Source: src/private/validation/Get-KeepAChangelogReleaseVersionList.ps1
function Get-KeepAChangelogReleaseVersionList {
    [CmdletBinding()]
    [OutputType([object[]])]
    param(
        [Parameter(Mandatory)]
        [string]$Body,
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [System.Collections.Generic.List[string]]$ErrorList
    )

    $releaseVersionList = [System.Collections.Generic.List[string]]::new()

    foreach ($releaseHeadingLine in [regex]::Matches($Body, '(?m)^##\s+\[(?<label>[^\]]+)\].*$')) {
        $label = $releaseHeadingLine.Groups['label'].Value
        if ($label -eq 'Unreleased') {
            continue
        }

        $line = $releaseHeadingLine.Value.TrimEnd()
        if ($line -notmatch '^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}( \[YANKED\])?$') {
            $ErrorList.Add("Release section '$line' must use '## [<version>] - <date>' format, optionally followed by ' [YANKED]'.")
            continue
        }

        if ($releaseVersionList.Contains($label)) {
            $ErrorList.Add("Release section [$label] is duplicated.")
            continue
        }

        $releaseVersionList.Add($label)
    }

    return ,$releaseVersionList
}


# Source: src/private/validation/Get-KeepAChangelogUnreleasedCompareLinkData.ps1
function Get-KeepAChangelogUnreleasedCompareLinkData {
    [CmdletBinding()]
    param(
        [AllowEmptyString()]
        [string]$Footer,
        [switch]$HasReferenceFooter,
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [System.Collections.Generic.List[string]]$ErrorList
    )

    $result = [pscustomobject]@{
        UnreleasedCompareLinkPrefix = $null
        UnreleasedTargetReference   = $null
        PreviousReleaseReference    = $null
    }

    if (-not $HasReferenceFooter) {
        return $result
    }

    $patternList = @(
        '(?m)^\[Unreleased\]:\s*(?<prefix>\S+/(?:compare|-/compare)/)(?<from>.+?)\.\.\.(?<target>HEAD)\s*$',
        '(?m)^\[Unreleased\]:\s*(?<prefix>\S+/branchCompare\?baseVersion=)(?<from>.+?)(?:&|&amp;)targetVersion=(?<target>.+?)(?:&|&amp;)_a=commits\s*$'
    )
    $matchList = [System.Collections.Generic.List[System.Text.RegularExpressions.Match]]::new()

    foreach ($pattern in $patternList) {
        foreach ($match in [regex]::Matches($Footer, $pattern)) {
            $matchList.Add($match)
        }
    }

    if ($matchList.Count -eq 0) {
        $ErrorList.Add('Could not find an [Unreleased] compare link in CHANGELOG.md.')
        return $result
    }

    if ($matchList.Count -gt 1) {
        $ErrorList.Add('CHANGELOG.md must contain exactly one [Unreleased] compare link.')
    }

    $match = $matchList[0]
    return [pscustomobject]@{
        UnreleasedCompareLinkPrefix = $match.Groups['prefix'].Value
        UnreleasedTargetReference   = $match.Groups['target'].Value
        PreviousReleaseReference    = $match.Groups['from'].Value
    }
}


# Source: src/private/validation/Get-KeepAChangelogUnreleasedSectionError.ps1
function Get-KeepAChangelogUnreleasedSectionError {
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [string]$Body
    )

    if (Test-KeepAChangelogHasUnreleasedSection -Body $Body) {
        return $null
    }

    $nearMatch = Find-KeepAChangelogNearUnreleasedSectionHeading -Body $Body
    if ($null -ne $nearMatch) {
        return "Found an Unreleased heading, but it is formatted as ``$nearMatch``. Expected ``## [Unreleased]``."
    }

    return 'Could not find ## [Unreleased] section in CHANGELOG.md.'
}

function Find-KeepAChangelogNearUnreleasedSectionHeading {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Body
    )

    foreach ($headingLine in Get-KeepAChangelogHeadingCandidateList -Body $Body) {
        if (Test-KeepAChangelogNearUnreleasedHeading -HeadingLine $headingLine) {
            return $headingLine
        }
    }

    return $null
}

function Get-KeepAChangelogHeadingCandidateList {
    [CmdletBinding()]
    [OutputType([object[]])]
    param(
        [Parameter(Mandatory)]
        [string]$Body
    )

    $headingLineList = [System.Collections.Generic.List[string]]::new()
    foreach ($headingMatch in [regex]::Matches($Body, '(?m)^#{1,6}\s+.+$')) {
        $headingLineList.Add($headingMatch.Value.TrimEnd())
    }

    return @($headingLineList.ToArray())
}

function Test-KeepAChangelogNearUnreleasedHeading {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$HeadingLine
    )

    $headingText = Get-KeepAChangelogHeadingText -HeadingLine $HeadingLine
    $normalizedHeadingText = Get-KeepAChangelogNormalizedUnreleasedHeadingText -HeadingText $headingText
    return $normalizedHeadingText -ceq 'Unreleased'
}

function Get-KeepAChangelogHeadingText {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$HeadingLine
    )

    return ($HeadingLine -replace '^\s*#+\s*', '').Trim()
}

function Get-KeepAChangelogNormalizedUnreleasedHeadingText {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$HeadingText
    )

    $normalizedHeadingText = $HeadingText.Trim()
    $wrapperPatternList = @(
        '^\[(.+)\]$',
        '^\{(.+)\}$',
        '^\((.+)\)$'
    )

    foreach ($wrapperPattern in $wrapperPatternList) {
        if ($normalizedHeadingText -match $wrapperPattern) {
            $normalizedHeadingText = $Matches[1].Trim()
            break
        }
    }

    return (Get-Culture).TextInfo.ToTitleCase($normalizedHeadingText.ToLowerInvariant())
}


# Source: src/private/validation/Get-KeepAChangelogValidationResult.ps1
function Get-KeepAChangelogValidationResult {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Text
    )

    $errorList = [System.Collections.Generic.List[string]]::new()
    $parts = Split-KeepAChangelogText -Text $Text
    $unreleasedSectionError = Get-KeepAChangelogUnreleasedSectionError -Body $parts.Body
    if ($null -ne $unreleasedSectionError) {
        $errorList.Add($unreleasedSectionError)
    }

    $releaseVersionList = Get-KeepAChangelogReleaseVersionList `
        -Body $parts.Body `
        -ErrorList $errorList
    $hasReferenceFooter = -not [string]::IsNullOrWhiteSpace($parts.Footer)

    $referenceLabelCountMap = Get-KeepAChangelogReferenceLabelCountMap -Footer $parts.Footer
    Add-KeepAChangelogDuplicateReferenceLinkError `
        -ReferenceLabelCountMap $referenceLabelCountMap `
        -ErrorList $errorList

    $unreleasedCompareLinkData = Get-KeepAChangelogUnreleasedCompareLinkData `
        -Footer $parts.Footer `
        -HasReferenceFooter:$hasReferenceFooter `
        -ErrorList $errorList

    return [pscustomobject]@{
        IsValid                     = ($errorList.Count -eq 0)
        Errors                      = @($errorList.ToArray())
        UnreleasedCompareLinkPrefix = $unreleasedCompareLinkData.UnreleasedCompareLinkPrefix
        UnreleasedTargetReference   = $unreleasedCompareLinkData.UnreleasedTargetReference
        PreviousReleaseReference    = $unreleasedCompareLinkData.PreviousReleaseReference
        ReleaseVersions             = @($releaseVersionList.ToArray())
    }
}


# Source: src/private/validation/Get-UnreleasedCompareLinkMatch.ps1
function Get-UnreleasedCompareLinkMatch {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Text
    )

    $patternList = @(
        '(?m)^\[Unreleased\]:\s*(?<prefix>\S+/(?:compare|-/compare)/)(?<from>.+?)\.\.\.(?<target>HEAD)\s*$',
        '(?m)^\[Unreleased\]:\s*(?<prefix>\S+/branchCompare\?baseVersion=)(?<from>.+?)(?:&|&amp;)targetVersion=(?<target>.+?)(?:&|&amp;)_a=commits\s*$'
    )
    $match = $null

    foreach ($pattern in $patternList) {
        $candidateMatch = [regex]::Match($Text, $pattern)
        if ($candidateMatch.Success) {
            $match = $candidateMatch
            break
        }
    }

    if ($null -eq $match -or -not $match.Success) {
        throw 'Could not find an [Unreleased] compare link in CHANGELOG.md.'
    }

    return $match
}


# Source: src/private/validation/Test-KeepAChangelogHasUnreleasedSection.ps1
function Test-KeepAChangelogHasUnreleasedSection {
    [CmdletBinding()]
    [OutputType([bool])]
    param(
        [Parameter(Mandatory)]
        [string]$Body
    )

    return [regex]::IsMatch($Body, '(?ms)^##\s+\[Unreleased\]\s*\r?\n')
}