diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index a936c4e8..1764656a 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -2,7 +2,7 @@ name: Docs # Builds the documentation site on every push to master and publishes it to GitHub Pages. # Pull requests and manual runs build the site too, but only master pushes and manual runs deploy. -# Warnings never block a deploy; an error, a library build error or a broken docs sample does, +# Warnings never block a deploy; an error, a library build error, a broken docs sample or a broken link does, # and in that case the previously published site stays live. on: @@ -63,6 +63,9 @@ jobs: if ($apiPages -lt 100) { throw "Only $apiPages API pages were generated" } "Site has $apiPages API pages." + - name: Check the links (a broken page, file or anchor fails the run; an external link fails it only on a hard 404 or 410) + run: ./docsite/tools/check-links.ps1 + - name: Summarize warnings if: always() continue-on-error: true diff --git a/README.md b/README.md index 04fd45f6..eb8e0330 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ The timing ratios are indicative. Sources, conditions and error margins: [Perfor - [SQL Server](https://open-net-libraries.github.io/Open.Database.Extensions/articles/getting-started.html#with-sql-server): `SqlConnectionFactory` and stored procedures on `Microsoft.Data.SqlClient`. - [Coming from Dapper](https://open-net-libraries.github.io/Open.Database.Extensions/articles/coming-from-dapper.html): the same jobs side by side. - [How little code](https://open-net-libraries.github.io/Open.Database.Extensions/articles/how-little-code.html): four tasks in ODX, Dapper, EF Core and plain ADO.NET. -- [Trimming and native AOT](https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/Source/Core/README.md#trimming-and-native-aot). +- [Trimming and native AOT](https://open-net-libraries.github.io/Open.Database.Extensions/articles/mapping.html#trimming-and-native-aot). Upgrading from an earlier version? See [Coming from earlier versions](https://open-net-libraries.github.io/Open.Database.Extensions/articles/whats-new-11.html). diff --git a/docsite/CONTRIBUTING-DOCS.md b/docsite/CONTRIBUTING-DOCS.md index b659c216..dd5e808e 100644 --- a/docsite/CONTRIBUTING-DOCS.md +++ b/docsite/CONTRIBUTING-DOCS.md @@ -12,4 +12,5 @@ Every push to `master` rebuilds and publishes the site (`.github/workflows/docs. - **Package READMEs:** each `Source//README.md` is the page nuget.org shows for that package (`Source/Directory.Build.props` packs the one beside the `.csproj`). Absolute links only, code blocks copied from sample regions. The "The packages" table is the same in every one of them: change it in all of them together. - **Package heroes:** the banner directly under the H1 of each package README is `docsite/images/hero-.svg` (1280 by 200; Core is 260). Left column: the ODX mark (a database and the letters ODX, in the package's accent color) with the package name; then the tagline; then a small scene. ODX is the acronym and the mark, not the name. The site name (`_appName` and `_appTitle` in `docfx.json`) and the H1 of the root `README.md` say "Open.Database.Extensions (ODX)"; the landing page `docsite/index.md` has no H1, by design (the header shows the name and the banner says what the library is, with its alt text as the accessible name; its front matter `title` is the browser-tab title); the package README H1s and all prose keep the full name Open.Database.Extensions. The banner's alt text carries the tagline; never repeat the tagline as text next to a banner. Each is linked by its absolute `raw.githubusercontent.com` URL because nuget.org shows only images from allow-listed hosts (that host is one). Each paints its own soft background in a light and a dark palette (`prefers-color-scheme`), because nuget.org's page theme can differ from the operating system's; keep the contrast soft and any motion subtle (`prefers-reduced-motion` turns it off). - **Build locally:** `dotnet tool restore`, then `dotnet docfx docsite/docfx.json --serve`. -- **Failures:** warnings are listed in the workflow summary and never block a deploy. A DocFX error or a sample that does not compile does, and the live site stays as it was. \ No newline at end of file +- **Links:** `docsite/tools/check-links.ps1` checks the built site and the six README files (the root one and the five package ones): every page, file and anchor must resolve, a README link must be absolute, a link into this repository's `master` branch (or the ref a pull request builds from, which DocFX uses for its "View source" links) is checked against the checkout, and an external link fails the run only on a hard 404 or 410 (a timeout or a refusal is listed, not failed). Run it after the local build: `pwsh docsite/tools/check-links.ps1` (add `-SkipExternal` to skip the network). +- **Failures:** warnings are listed in the workflow summary and never block a deploy. A DocFX error, a sample that does not compile or a broken link does, and the live site stays as it was. \ No newline at end of file diff --git a/docsite/tools/check-links.ps1 b/docsite/tools/check-links.ps1 new file mode 100644 index 00000000..31d5098f --- /dev/null +++ b/docsite/tools/check-links.ps1 @@ -0,0 +1,293 @@ +<# +.SYNOPSIS + Checks the links of the built documentation site and of the package READMEs. + +.DESCRIPTION + Internal links (page, file, anchor) must resolve, or the script fails. + External links are checked too, and fail the run only on a hard 404 or 410; any other answer + (a timeout, a 403, a 429, a 5xx) is reported and never fails the run, because a network + fault is not a broken link. + + What it reads: + - every .html page under -Site (a, img, link and script tags); + - the README.md files named by -Markdown (links, images and tags). A README link must be absolute + (nuget.org shows the README away from the repository, so a relative link is dead there); + one that points into the published site is checked against -Site, and one that points at this + repository's master branch (github.com blob or tree, raw.githubusercontent.com) is checked against + the checkout, so a file added in a pull request is found before it is merged. + + Links from API reference pages to learn.microsoft.com are generated by DocFX from the framework's + cross-reference map; they are not checked. + +.PARAMETER Site + The built site (the DocFX output folder). + +.PARAMETER Repo + The repository checkout, used for the README links that point at this repository. Those are looked up among + the files git tracks (a case-sensitive match, as on GitHub), so a new file needs git add first. + +.PARAMETER Markdown + Markdown files whose links are checked, relative to -Repo. Default: the root README and the package READMEs. + +.PARAMETER SkipExternal + Check internal links only (a quick local run). + +.EXAMPLE + dotnet docfx docsite/docfx.json + pwsh docsite/tools/check-links.ps1 +#> +#Requires -Version 7.0 +[CmdletBinding()] +param( + [string]$Site = (Join-Path $PSScriptRoot '..\_site'), + [string]$Repo = (Join-Path $PSScriptRoot '..\..'), + [string[]]$Markdown = @('README.md', 'Source/Core/README.md', 'Source/MSSqlClient/README.md', 'Source/Channel/README.md', 'Source/Dataflow/README.md', 'Source/Extensions/README.md'), + [switch]$SkipExternal, + [int]$Parallel = 6 +) + +$ErrorActionPreference = 'Stop' +$Site = (Resolve-Path $Site).Path.TrimEnd('\', '/') +$Repo = (Resolve-Path $Repo).Path.TrimEnd('\', '/') + +$publishedBase = 'https://open-net-libraries.github.io/Open.Database.Extensions/' +# A link into this repository on GitHub: the master branch, or the ref a pull request is built from +# (DocFX writes its "View source" links with the ref the build ran on, e.g. 330/merge). +$repoWebPattern = [regex]::new('^https://(?:github\.com/Open-NET-Libraries/Open\.Database\.Extensions/(?:blob|tree)|raw\.githubusercontent\.com/Open-NET-Libraries/Open\.Database\.Extensions)/(?:master|\d+/merge|\d+/head)/', 'IgnoreCase') + +$internalErrors = [System.Collections.Generic.List[string]]::new() +# Each external link once, with the pages that carry it. +$external = [System.Collections.Generic.Dictionary[string, System.Collections.Generic.List[string]]]::new() +$anchorCache = [System.Collections.Generic.Dictionary[string, System.Collections.Generic.HashSet[string]]]::new() + +function Get-Anchors([string]$file) { + if ($anchorCache.ContainsKey($file)) { return $anchorCache[$file] } + $set = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + $text = [System.IO.File]::ReadAllText($file) + foreach ($m in [regex]::Matches($text, '<(?:[a-zA-Z][a-zA-Z0-9-]*\b[^>]*?\sid|a\b[^>]*?\sname)\s*=\s*(?:"([^"]*)"|''([^'']*)'')')) { + $v = if ($m.Groups[1].Success) { $m.Groups[1].Value } else { $m.Groups[2].Value } + [void]$set.Add([System.Net.WebUtility]::HtmlDecode($v)) + } + # The presentation is a slide deck: its script reads #N as "slide N", so 1..slide count are valid targets. + $slides = [regex]::Matches($text, ']*\bclass\s*=\s*"[^"]*\bslide\b').Count + for ($n = 1; $n -le $slides; $n++) { [void]$set.Add([string]$n) } + $anchorCache[$file] = $set + return $set +} + +# The anchors GitHub gives a markdown file: one per heading (lower case, punctuation dropped, spaces to +# hyphens, -1 -2 on repeats) and any explicit id or name. +function Get-MarkdownAnchors([string]$file) { + if ($anchorCache.ContainsKey($file)) { return $anchorCache[$file] } + $set = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + $text = [regex]::Replace([System.IO.File]::ReadAllText($file), '(?ms)^[ \t]*(```|~~~).*?^[ \t]*\1', '') + $seen = @{} + foreach ($m in [regex]::Matches($text, '(?m)^ {0,3}#{1,6}[ \t]+(.+?)[ \t#]*$')) { + $h = $m.Groups[1].Value + $h = [regex]::Replace($h, '!?\[([^\]]*)\]\([^)]*\)', '$1') + # Emphasis marks are dropped; an underscore between letters or digits is part of the word and stays. + $h = ($h -replace '[`*~]', '') -replace '(?]*?\s(?:id|name)\s*=\s*"([^"]*)"')) { [void]$set.Add($m.Groups[1].Value) } + $anchorCache[$file] = $set + return $set +} + +function Add-External([string]$url, [string]$from) { + if (-not $external.ContainsKey($url)) { $external[$url] = [System.Collections.Generic.List[string]]::new() } + if ($external[$url].Count -lt 3 -and -not $external[$url].Contains($from)) { $external[$url].Add($from) } +} + +# GitHub Pages and GitHub match file names by case; Windows does not. Both lookups below are case-sensitive, +# so a link that only works on a case-insensitive disk is reported. +$siteFiles = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) +foreach ($p in [System.IO.Directory]::GetFiles($Site, '*', [System.IO.SearchOption]::AllDirectories)) { + [void]$siteFiles.Add($p.Substring($Site.Length + 1).Replace('\', '/')) +} +# The files of the repository are the ones git tracks, so git is required (a disk check would ignore case on Windows). +if (-not (Get-Command git -ErrorAction SilentlyContinue)) { throw 'git is required: the files this repository holds are the ones git tracks.' } +$repoPaths = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) +$tracked = @(git -C $Repo -c core.quotepath=off ls-files) +if ($LASTEXITCODE -ne 0 -or $tracked.Count -eq 0) { throw "git lists no files under $Repo; -Repo must be a git checkout." } +foreach ($p in $tracked) { + [void]$repoPaths.Add($p) + for ($i = $p.LastIndexOf('/'); $i -gt 0; $i = $p.LastIndexOf('/', $i - 1)) { [void]$repoPaths.Add($p.Substring(0, $i)) } +} + +# Resolves a path inside the site (no query, no fragment) to a file, or $null. +function Resolve-SitePath([string]$path) { + $rel = [System.Uri]::UnescapeDataString($path).Trim('/') + $found = if ($rel -ne '' -and $siteFiles.Contains($rel)) { $rel } + elseif ($siteFiles.Contains(($rel + '/index.html').TrimStart('/'))) { ($rel + '/index.html').TrimStart('/') } + elseif ($rel -ne '' -and $siteFiles.Contains($rel + '.html')) { $rel + '.html' } + if ($found) { return (Join-Path $Site $found.Replace('/', [System.IO.Path]::DirectorySeparatorChar)) } + return $null +} + +# One link found on a page or in a README. $source is a label for messages; $pageUri is the page's own URL +# (a relative link resolves against it); $allowRelative is $false for a README. +function Test-Link([string]$raw, [string]$source, [uri]$pageUri, [bool]$allowRelative, [bool]$fromApiPage) { + $href = [System.Net.WebUtility]::HtmlDecode($raw).Trim() + if ($href -eq '' -or $href.StartsWith('#!') ) { return } + if ($href -match '^(mailto:|javascript:|tel:|data:)') { return } + + $isAbsolute = $href -match '^[a-zA-Z][a-zA-Z0-9+.-]*:' -or $href.StartsWith('//') + if (-not $isAbsolute -and -not $allowRelative) { + $internalErrors.Add("${source}: relative link '$href' (a README link must be absolute)") + return + } + + $uri = $null + if (-not [System.Uri]::TryCreate($pageUri, $href, [ref]$uri) -or -not $uri.IsAbsoluteUri) { + $internalErrors.Add("${source}: cannot read the link '$href'") + return + } + + $absolute = $uri.AbsoluteUri + $fragment = [System.Uri]::UnescapeDataString($uri.Fragment).TrimStart('#') + + # A link into this repository on GitHub is checked against the checkout. + $repoLink = $repoWebPattern.Match($absolute) + if ($repoLink.Success) { + $relative = [System.Uri]::UnescapeDataString($absolute.Substring($repoLink.Length).Split('?')[0].Split('#')[0]) + $local = Join-Path $Repo ($relative.Replace('/', [System.IO.Path]::DirectorySeparatorChar)) + $exists = ($relative.Trim('/') -eq '') -or $repoPaths.Contains($relative.Trim('/')) + if (-not $exists) { + $internalErrors.Add("${source}: '$href' points at '$relative', which is not in the repository") + } + elseif ($fragment -ne '' -and $relative.EndsWith('.md', [System.StringComparison]::OrdinalIgnoreCase) -and [System.IO.File]::Exists($local)) { + if (-not (Get-MarkdownAnchors $local).Contains($fragment)) { + $internalErrors.Add("${source}: '$href' has no heading or id '$fragment' in '$relative'") + } + } + return + } + + # The site's own address without its trailing slash is the site's start page. + if ($absolute -eq $publishedBase.TrimEnd('/')) { $absolute = $publishedBase } + $isSite = $absolute.StartsWith($publishedBase, [System.StringComparison]::OrdinalIgnoreCase) -or + ($uri.Scheme -eq 'file') -or ($uri.Host -eq 'site.test') + if ($isSite) { + $path = if ($uri.Scheme -eq 'file' -or $uri.Host -eq 'site.test') { $uri.AbsolutePath } else { $absolute.Substring($publishedBase.Length).Split('?')[0].Split('#')[0] } + $file = Resolve-SitePath $path + if (-not $file) { $internalErrors.Add("${source}: '$href' does not resolve to a page or file"); return } + if ($fragment -ne '' -and -not $fragment.StartsWith(':~:') -and $file.EndsWith('.html', [System.StringComparison]::OrdinalIgnoreCase)) { + if (-not (Get-Anchors $file).Contains($fragment)) { + $internalErrors.Add("${source}: '$href' has no anchor '$fragment' on the target page") + } + } + return + } + + if ($uri.Scheme -ne 'http' -and $uri.Scheme -ne 'https') { return } + if ($uri.Host -in 'localhost', '127.0.0.1', 'example.com', 'example.org', 'www.example.com') { return } + if ($fromApiPage -and $uri.Host -eq 'learn.microsoft.com') { return } + Add-External ($absolute -replace '#.*$', '') $source +} + +# ---- the built site --------------------------------------------------------------------------------- +$pages = [System.IO.Directory]::GetFiles($Site, '*.html', [System.IO.SearchOption]::AllDirectories) +if ($pages.Count -lt 100) { throw "Only $($pages.Count) pages under $Site; build the site first." } +"Checking $($pages.Count) pages under $Site ..." +$tagPattern = [regex]::new('<(?:a|img|link|script|source)\b[^>]*?\b(?:href|src)\s*=\s*(?:"([^"]*)"|''([^'']*)'')', 'IgnoreCase') +$linkCount = 0 +foreach ($page in $pages) { + $relPage = $page.Substring($Site.Length + 1).Replace('\', '/') + $pageUri = [uri]('https://site.test/' + [System.Uri]::EscapeUriString($relPage)) + $fromApi = $relPage.StartsWith('api/', [System.StringComparison]::Ordinal) + $text = [System.IO.File]::ReadAllText($page) + # A preconnect or dns-prefetch hint names a host, not a page: its URL has nothing to fetch. + $text = [regex]::Replace($text, ']*\brel\s*=\s*["''](?:preconnect|dns-prefetch)["''][^>]*>', '', 'IgnoreCase') + foreach ($m in $tagPattern.Matches($text)) { + $value = if ($m.Groups[1].Success) { $m.Groups[1].Value } else { $m.Groups[2].Value } + $linkCount++ + Test-Link $value $relPage $pageUri $true $fromApi + } +} +" $linkCount links on the pages." + +# ---- the README files ------------------------------------------------------------------------------- +foreach ($md in $Markdown) { + $file = Join-Path $Repo $md + if (-not [System.IO.File]::Exists($file)) { $internalErrors.Add("${md}: file not found"); continue } + $text = [System.IO.File]::ReadAllText($file) + # Fenced code is not prose: its brackets are code, not links. + $text = [regex]::Replace($text, '(?ms)^[ \t]*(```|~~~).*?^[ \t]*\1', '') + $text = [regex]::Replace($text, '`[^`\r\n]*`', '') + $found = 0 + # Every "](destination)": a plain link or image, and both halves of a linked image such as [![alt](image)](target). + foreach ($m in [regex]::Matches($text, '\]\(\s*]|\([^()\s]*\))+)>?(?:\s+"[^"]*")?\s*\)')) { + $found++; Test-Link $m.Groups[1].Value $md ([uri]'https://readme.test/') $false $false + } + foreach ($m in [regex]::Matches($text, '<(?:a|img)\b[^>]*?\b(?:href|src)\s*=\s*(?:"([^"]*)"|''([^'']*)'')', 'IgnoreCase')) { + $value = if ($m.Groups[1].Success) { $m.Groups[1].Value } else { $m.Groups[2].Value } + $found++; Test-Link $value $md ([uri]'https://readme.test/') $false $false + } + foreach ($m in [regex]::Matches($text, '(?m)^\[[^\]]+\]:\s*]+)')) { + $found++; Test-Link $m.Groups[1].Value $md ([uri]'https://readme.test/') $false $false + } + " ${md}: $found links." +} + +# ---- external links --------------------------------------------------------------------------------- +$hard = [System.Collections.Generic.List[string]]::new() +$soft = [System.Collections.Generic.List[string]]::new() +if ($SkipExternal) { + "External links: $($external.Count) found, not checked (-SkipExternal)." +} +else { + "Checking $($external.Count) external links ..." + $urls = @($external.Keys | Sort-Object) + # A network fault must not stall the run: each request waits 10 seconds at most, a timeout or a 5xx is tried + # twice, and after $deadline every URL not yet asked is listed as not checked. + $deadline = [datetime]::UtcNow.AddMinutes(5) + $results = $urls | ForEach-Object -ThrottleLimit $Parallel -Parallel { + $url = $_ + $status = 0; $note = '' + if ([datetime]::UtcNow -gt $using:deadline) { + return [pscustomobject]@{ Url = $url; Status = 0; Note = 'not checked: the time limit for external links was reached' } + } + for ($try = 1; $try -le 2; $try++) { + $status = 0; $note = '' + try { + $r = Invoke-WebRequest -Uri $url -Method Head -SkipHttpErrorCheck -TimeoutSec 10 -MaximumRedirection 8 -UserAgent 'docs-link-check' -ErrorAction Stop + $status = [int]$r.StatusCode + } + catch { $note = $_.Exception.Message } + # A server that refuses HEAD says nothing about the page: ask again with GET (only when it answered at all). + if ($status -ge 400) { + try { + $r = Invoke-WebRequest -Uri $url -Method Get -SkipHttpErrorCheck -TimeoutSec 10 -MaximumRedirection 8 -UserAgent 'docs-link-check' -ErrorAction Stop + $status = [int]$r.StatusCode + } + catch { $note = $_.Exception.Message } # the HEAD answer stays: a GET that times out does not undo a 404 + } + # Only a timeout or a server error is worth another try. + if ($status -ne 0 -and $status -lt 500) { break } + Start-Sleep -Seconds 2 + } + [pscustomobject]@{ Url = $url; Status = $status; Note = $note } + } + foreach ($r in $results) { + $where = ($external[$r.Url] -join ', ') + if ($r.Status -eq 404 -or $r.Status -eq 410) { $hard.Add("$($r.Url) -> $($r.Status) (on $where)") } + elseif ($r.Status -lt 200 -or $r.Status -ge 400) { $soft.Add("$($r.Url) -> $(if ($r.Status) { $r.Status } else { $r.Note }) (on $where)") } + } +} + +# ---- report ----------------------------------------------------------------------------------------- +$lines = [System.Collections.Generic.List[string]]::new() +$lines.Add('## Link check') +$lines.Add('') +$lines.Add("Internal links: **$($internalErrors.Count)** broken. External links: **$($hard.Count)** hard 404 or 410, $($soft.Count) not confirmed (reported, never failing).") +if ($internalErrors.Count -gt 0) { $lines.Add(''); $lines.Add('### Broken internal links'); $internalErrors | Sort-Object -Unique | ForEach-Object { $lines.Add("- $_") } } +if ($hard.Count -gt 0) { $lines.Add(''); $lines.Add('### Broken external links (404 or 410)'); $hard | Sort-Object | ForEach-Object { $lines.Add("- $_") } } +if ($soft.Count -gt 0) { $lines.Add(''); $lines.Add('### External links not confirmed (not failing)'); $soft | Sort-Object | ForEach-Object { $lines.Add("- $_") } } +$lines | ForEach-Object { $_ } +if ($env:GITHUB_STEP_SUMMARY) { $lines -join "`n" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8 } + +if ($internalErrors.Count -gt 0 -or $hard.Count -gt 0) { exit 1 } +exit 0