Private/Test-GhostSiteLinkMatch.ps1
|
function Test-GhostSiteLinkMatch { <# .SYNOPSIS Tells whether the text of a file is the text of the site, apart from the address of the site in links. .DESCRIPTION A file can link to another page of the same site without the address of the site, [text](/a-page/) or <a href="/a-page/">, so that the link also works on a local site. Ghost gives such a link back with the address of the site in it. Test-GhostPostChange and Compare-GhostPostFile use this function, so that such a file is not taken for a file that differs from its post. The answer is true when the two texts are the same, and also when they only differ in this: the file has a link without the address of the site where the site has the same link with it. A link with the address in both is the same link too, with http or https and with or without www. in either of them. A file that has the address where the site has none differs, and so does every other difference. A link is looked for where Ghost writes the address: - The destination of a Markdown link or image, [text](/a-page/). - The href, src and srcset of an HTML element, in double or single quotes. - A reference definition, [name]: /a-page/. Ghost leaves that one as it is, and it is read here in case a version of Ghost does not. Code, a fenced block or a code span, is text about a link and is compared as it is. So is a Markdown link in a block of HTML, which Markdown does not read. Get-MarkdownImage reads code and HTML the same way. A path from the root of the site starts with one slash: //example.org is another site. Ghost also rewrites the path of such a link the way a browser does, /a/../b/ to /b/ and an accented letter to its code. A link like that still differs, so write it the way Ghost stores it. Both texts are expected to have line feeds as line endings. .EXAMPLE Test-GhostSiteLinkMatch -Text '[a](/b/)' -Stored '[a](https://example.org/b/)' -SiteUrl 'https://example.org' Returns true: the file has the link of the site, without its address. .EXAMPLE Test-GhostSiteLinkMatch -Text '[a](/b/)' -Stored '[a](https://example.org/c/)' -SiteUrl 'https://example.org' Returns false: the link points to another page. #> [CmdletBinding()] [OutputType([bool])] param( # The text as the file has it. [Parameter(Mandatory)] [AllowEmptyString()] [string] $Text, # The text as the site gives it. [Parameter(Mandatory)] [AllowEmptyString()] [string] $Stored, # The addresses of the site, as Get-GhostSiteUrl returns them. Without one the texts have to be the same. [string[]] $SiteUrl = @() ) if ($Text -ceq $Stored) { return $true } # Every address as a pattern: with http or https, with or without www., and with the port and the folder # that the site has. $sites = @( foreach ($address in $SiteUrl) { $uri = $null $isAddress = [uri]::TryCreate($address, [System.UriKind]::Absolute, [ref] $uri) if (-not $isAddress -or @('http', 'https') -notcontains $uri.Scheme) { continue } $name = [regex]::Escape(($uri.Host -replace '^www\.', '')) if (-not $uri.IsDefaultPort) { $name = '{0}:{1}' -f $name, $uri.Port } 'https?://(?:www\.)?{0}{1}' -f $name, [regex]::Escape($uri.AbsolutePath.TrimEnd('/')) } ) if ($sites.Count -eq 0) { return $false } # Where a link begins: after the attribute of an HTML element, and in Markdown after the text of a link or # the name of a definition. In srcset every address after a comma is one. $attribute = '(?<![\w-])(?:href|src)\s*=\s*["'']|(?<![\w-])srcset\s*=\s*["''](?:[^"''<>]*,)?\s*' $markdown = '\]\([ \t]*\n?[ \t]*<?|^[ ]{0,3}\[(?:[^\[\]\\\n]|\\.)+\]:[ \t]*<?' # How a link to the site begins: with the address, which has the group site, or with the slash of a path # from the root. The address alone is the home page, which Ghost writes with a slash. $start = '(?:(?<site>{0})(?:/(?!/)|(?=[?#\s)>"'']|\z))|/(?!/))' -f ($sites -join '|') # A block of HTML and code come first, so that each is taken as a whole. They are the blocks of # Get-MarkdownImage. $literal = @' (?<html> ^[ ]{0,3}<(?:pre|script|style|textarea)(?=[\s>]|\z)(?s:.*?)(?:</(?:pre|script|style|textarea)>[^\n]*|\z) | ^[ ]{0,3}<!--(?s:.*?)(?:-->[^\n]*|\z) | ^[ ]{0,3}</?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details |dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html |iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section |summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?=[\s>]|/>|\z) (?s:.*?)(?=\n[ \t]*(?:\n|\z)|\z) ) | (?<code> ^[ ]{0,3}(?<fence>`{3,}|~{3,})[^\n]*\n(?s:.*?)(?:^[ ]{0,3}\k<fence>[`~]*[ \t]*$|\z) | (?<!`)(?<ticks>`+)(?!`)(?s:.+?)(?<!`)\k<ticks>(?!`) ) '@ $options = [System.Text.RegularExpressions.RegexOptions] 'IgnorePatternWhitespace, Multiline, IgnoreCase' $inHtml = [regex]::new(('(?=[/h])(?<={0}){1}' -f $attribute, $start), $options) $inText = [regex]::new(('{0} | (?=[/h])(?<={1}|{2}){3}' -f $literal, $attribute, $markdown, $start), $options) # Each text without the address of the site, and for every link its place there and whether it had the # address. $read = @( foreach ($value in $Text, $Stored) { $plain = [System.Text.StringBuilder]::new() $links = [System.Collections.Generic.List[object]]::new() $position = 0 foreach ($match in $inText.Matches($value)) { if ($match.Groups['code'].Success) { continue } # In a block of HTML only the attributes of its elements are links. $found = @($match) $offset = 0 if ($match.Groups['html'].Success) { $found = @($inHtml.Matches($match.Value)) $offset = $match.Index } foreach ($link in $found) { # Substring, because Append with a start and a length is slow on PowerShell 7 for a long # text. $index = $offset + $link.Index $plain.Append($value.Substring($position, $index - $position)).Append('/') | Out-Null $links.Add([pscustomobject]@{ Index = $plain.Length; Site = $link.Groups['site'].Success }) $position = $index + $link.Length } } $plain.Append($value.Substring($position)) | Out-Null [pscustomobject]@{ Text = $plain.ToString(); Links = $links } } ) $file = $read[0] $site = $read[1] if ($file.Text -cne $site.Text -or $file.Links.Count -ne $site.Links.Count) { return $false } for ($index = 0; $index -lt $file.Links.Count; $index++) { # The same link at the same place. Only the file may be the one without the address. $same = $file.Links[$index].Index -eq $site.Links[$index].Index if (-not $same -or ($file.Links[$index].Site -and -not $site.Links[$index].Site)) { return $false } } $true } |