From dec58529a0159df017fa66b32e47dfd55df0582d Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:36:26 -0800 Subject: [PATCH 1/4] Check the links of the built docs site and the package READMEs in docs.yml docsite/tools/check-links.ps1 reads every page of the built site and the six README files. An internal page, file or anchor that does not resolve fails the run, as does a README link that is not absolute. A README link into this repository's master branch is checked against the checkout (so a file added in a pull request is found before it merges), and every lookup is case-sensitive, as on GitHub Pages. An external link fails the run only on a hard 404 or 410; a timeout or a refusal is listed and not failed. Slide links (#N) in the presentation are checked against the slide count, preconnect hints are not links, and API-page links to learn.microsoft.com (generated by DocFX) are skipped. The check is a small PowerShell script rather than a third-party action: it needs no pinned external dependency, runs the same locally and in CI, and knows the three site-specific cases above. It found no broken link in the current tree (626 pages, 17742 links, 13 external). Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/docs.yml | 5 +- docsite/CONTRIBUTING-DOCS.md | 3 +- docsite/tools/check-links.ps1 | 252 ++++++++++++++++++++++++++++++++++ 3 files changed, 258 insertions(+), 2 deletions(-) create mode 100644 docsite/tools/check-links.ps1 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/docsite/CONTRIBUTING-DOCS.md b/docsite/CONTRIBUTING-DOCS.md index b659c216..ab6c8c99 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 README link into this repository's `master` branch 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..af1c1aef --- /dev/null +++ b/docsite/tools/check-links.ps1 @@ -0,0 +1,252 @@ +<# +.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 +#> +[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/' +$repoWebPrefixes = @( + 'https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/', + 'https://github.com/Open-NET-Libraries/Open.Database.Extensions/tree/master/', + 'https://raw.githubusercontent.com/Open-NET-Libraries/Open.Database.Extensions/master/' +) + +$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, '\s(?:id|name)\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 +} + +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('\', '/')) +} +$repoPaths = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) +$tracked = @(git -C $Repo -c core.quotepath=off ls-files 2>$null) +if ($LASTEXITCODE -eq 0 -and $tracked.Count -gt 0) { + 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)) } + } +} +else { $repoPaths = $null } + +# 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('/') } + 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's master branch is checked against the checkout. + foreach ($prefix in $repoWebPrefixes) { + if ($absolute.StartsWith($prefix, [System.StringComparison]::Ordinal)) { + $relative = [System.Uri]::UnescapeDataString($absolute.Substring($prefix.Length)).Split('?')[0].Split('#')[0] + $local = Join-Path $Repo ($relative.Replace('/', [System.IO.Path]::DirectorySeparatorChar)) + $exists = if ($null -ne $repoPaths) { $repoPaths.Contains($relative.Trim('/')) } else { [System.IO.File]::Exists($local) -or [System.IO.Directory]::Exists($local) } + if (-not $exists) { + $internalErrors.Add("${source}: '$href' points at '$relative', which is not in the repository") + } + return + } + } + + $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)^(```|~~~).*?^\1', '') + $text = [regex]::Replace($text, '`[^`\r\n]*`', '') + $found = 0 + foreach ($m in [regex]::Matches($text, '!?\[[^\]]*\]\(\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')) { + $found++; Test-Link $m.Groups[1].Value $md ([uri]'https://readme.test/') $false $false + } + foreach ($m in [regex]::Matches($text, '(?m)^\[[^\]]+\]:\s*(\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) + $results = $urls | ForEach-Object -ThrottleLimit $Parallel -Parallel { + $url = $_ + $status = 0; $note = '' + for ($try = 1; $try -le 3; $try++) { + foreach ($method in 'Head', 'Get') { + try { + $r = Invoke-WebRequest -Uri $url -Method $method -SkipHttpErrorCheck -TimeoutSec 25 -MaximumRedirection 8 -UserAgent 'docs-link-check' -ErrorAction Stop + $status = [int]$r.StatusCode; $note = '' + } + catch { $status = 0; $note = $_.Exception.Message } + # A HEAD that is refused says nothing about the page: ask again with GET. + if ($status -ge 200 -and $status -lt 400) { break } + } + if (($status -ge 200 -and $status -lt 400) -or $status -eq 404 -or $status -eq 410) { break } + Start-Sleep -Seconds (2 * $try) + } + [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 From f12f9680a8b915823f340868e626767048fd1882 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:39:15 -0800 Subject: [PATCH 2/4] Check README anchors on GitHub, bound the external checks, fix the one dead anchor found The link check now also looks up the heading of a README link into this repository's master branch (GitHub's heading ids), and found one real dead link: the root README sent "Trimming and native AOT" to a heading that Source/Core/README.md does not have. It now links to the article that holds the section. Review of the checker (three reviewers, arbitrated): a README link into the repository's root, a different case of the owner name, an extensionless published URL, a URL with parentheses, an indented code fence and an angle-bracket reference definition are read correctly; an id on a meta tag no longer counts as an anchor; external requests wait 10 seconds at most, retry only a timeout or a 5xx, and stop after 5 minutes in total, so a network fault cannot stall a deploy. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- docsite/tools/check-links.ps1 | 68 +++++++++++++++++++++++++++-------- 2 files changed, 54 insertions(+), 16 deletions(-) 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/tools/check-links.ps1 b/docsite/tools/check-links.ps1 index af1c1aef..a7f75575 100644 --- a/docsite/tools/check-links.ps1 +++ b/docsite/tools/check-links.ps1 @@ -65,7 +65,7 @@ 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, '\s(?:id|name)\s*=\s*(?:"([^"]*)"|''([^'']*)'')')) { + 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)) } @@ -76,6 +76,26 @@ function Get-Anchors([string]$file) { 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') + $h = $h -replace '[`*_~]', '' + $slug = ([regex]::Replace($h.ToLowerInvariant(), '[^\p{L}\p{N}\p{M}\s_-]', '')).Trim() -replace '\s', '-' + if ($seen.ContainsKey($slug)) { $seen[$slug]++; $slug = "$slug-$($seen[$slug])" } else { $seen[$slug] = 0 } + [void]$set.Add($slug) + } + foreach ($m in [regex]::Matches($text, '<[^>]*?\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) } @@ -102,6 +122,7 @@ 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 } @@ -130,13 +151,18 @@ function Test-Link([string]$raw, [string]$source, [uri]$pageUri, [bool]$allowRel # A link into this repository's master branch is checked against the checkout. foreach ($prefix in $repoWebPrefixes) { - if ($absolute.StartsWith($prefix, [System.StringComparison]::Ordinal)) { - $relative = [System.Uri]::UnescapeDataString($absolute.Substring($prefix.Length)).Split('?')[0].Split('#')[0] + if ($absolute.StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)) { + $relative = [System.Uri]::UnescapeDataString($absolute.Substring($prefix.Length).Split('?')[0].Split('#')[0]) $local = Join-Path $Repo ($relative.Replace('/', [System.IO.Path]::DirectorySeparatorChar)) - $exists = if ($null -ne $repoPaths) { $repoPaths.Contains($relative.Trim('/')) } else { [System.IO.File]::Exists($local) -or [System.IO.Directory]::Exists($local) } + $exists = if ($relative.Trim('/') -eq '') { $true } elseif ($null -ne $repoPaths) { $repoPaths.Contains($relative.Trim('/')) } else { [System.IO.File]::Exists($local) -or [System.IO.Directory]::Exists($local) } 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 } } @@ -188,16 +214,16 @@ foreach ($md in $Markdown) { 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)^(```|~~~).*?^\1', '') + $text = [regex]::Replace($text, '(?ms)^[ \t]*(```|~~~).*?^[ \t]*\1', '') $text = [regex]::Replace($text, '`[^`\r\n]*`', '') $found = 0 - foreach ($m in [regex]::Matches($text, '!?\[[^\]]*\]\(\s*]+)>?(?:\s+"[^"]*")?\s*\)')) { + 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')) { $found++; Test-Link $m.Groups[1].Value $md ([uri]'https://readme.test/') $false $false } - foreach ($m in [regex]::Matches($text, '(?m)^\[[^\]]+\]:\s*(\S+)')) { + 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." @@ -212,21 +238,33 @@ if ($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 = '' - for ($try = 1; $try -le 3; $try++) { - foreach ($method in 'Head', 'Get') { + 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 $method -SkipHttpErrorCheck -TimeoutSec 25 -MaximumRedirection 8 -UserAgent 'docs-link-check' -ErrorAction Stop - $status = [int]$r.StatusCode; $note = '' + $r = Invoke-WebRequest -Uri $url -Method Get -SkipHttpErrorCheck -TimeoutSec 10 -MaximumRedirection 8 -UserAgent 'docs-link-check' -ErrorAction Stop + $status = [int]$r.StatusCode } catch { $status = 0; $note = $_.Exception.Message } - # A HEAD that is refused says nothing about the page: ask again with GET. - if ($status -ge 200 -and $status -lt 400) { break } } - if (($status -ge 200 -and $status -lt 400) -or $status -eq 404 -or $status -eq 410) { break } - Start-Sleep -Seconds (2 * $try) + # 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 } } From c900dcc4934c54bb48f5c14696f966debd0c16bd Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:47:40 -0800 Subject: [PATCH 3/4] Check a pull request's DocFX "View source" links against the checkout, not on the network On a pull request DocFX writes its "View source" links with the ref the build ran on (github.com/.../blob/330/merge/Source/...), a ref that is not a branch, so the external check found 69 hard 404s on the first CI run. The local build has no such links. A link into this repository on GitHub whose ref is master, or /merge, or /head is now looked up among the files git tracks, as a link to master already was. Co-Authored-By: Claude Sonnet 5.5 --- docsite/CONTRIBUTING-DOCS.md | 2 +- docsite/tools/check-links.ps1 | 35 ++++++++++++++++------------------- 2 files changed, 17 insertions(+), 20 deletions(-) diff --git a/docsite/CONTRIBUTING-DOCS.md b/docsite/CONTRIBUTING-DOCS.md index ab6c8c99..dd5e808e 100644 --- a/docsite/CONTRIBUTING-DOCS.md +++ b/docsite/CONTRIBUTING-DOCS.md @@ -12,5 +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`. -- **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 README link into this repository's `master` branch 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). +- **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 index a7f75575..ba1d89ed 100644 --- a/docsite/tools/check-links.ps1 +++ b/docsite/tools/check-links.ps1 @@ -50,11 +50,9 @@ $Site = (Resolve-Path $Site).Path.TrimEnd('\', '/') $Repo = (Resolve-Path $Repo).Path.TrimEnd('\', '/') $publishedBase = 'https://open-net-libraries.github.io/Open.Database.Extensions/' -$repoWebPrefixes = @( - 'https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/', - 'https://github.com/Open-NET-Libraries/Open.Database.Extensions/tree/master/', - 'https://raw.githubusercontent.com/Open-NET-Libraries/Open.Database.Extensions/master/' -) +# 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. @@ -149,22 +147,21 @@ function Test-Link([string]$raw, [string]$source, [uri]$pageUri, [bool]$allowRel $absolute = $uri.AbsoluteUri $fragment = [System.Uri]::UnescapeDataString($uri.Fragment).TrimStart('#') - # A link into this repository's master branch is checked against the checkout. - foreach ($prefix in $repoWebPrefixes) { - if ($absolute.StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)) { - $relative = [System.Uri]::UnescapeDataString($absolute.Substring($prefix.Length).Split('?')[0].Split('#')[0]) - $local = Join-Path $Repo ($relative.Replace('/', [System.IO.Path]::DirectorySeparatorChar)) - $exists = if ($relative.Trim('/') -eq '') { $true } elseif ($null -ne $repoPaths) { $repoPaths.Contains($relative.Trim('/')) } else { [System.IO.File]::Exists($local) -or [System.IO.Directory]::Exists($local) } - 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'") - } + # 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 = if ($relative.Trim('/') -eq '') { $true } elseif ($null -ne $repoPaths) { $repoPaths.Contains($relative.Trim('/')) } else { [System.IO.File]::Exists($local) -or [System.IO.Directory]::Exists($local) } + 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 } + return } $isSite = $absolute.StartsWith($publishedBase, [System.StringComparison]::OrdinalIgnoreCase) -or From 116166500dbd3f384e8f82ae29b91ede2a2917cf Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:48:43 -0800 Subject: [PATCH 4/4] Fix the link checker findings of the swarm: check both halves of a linked image, keep a HEAD 404, and five smaller fixes - A linked image such as [![alt](image)](target) had its target never checked (the pattern needed a "[" before each "](...)"); both halves are checked now. - A HEAD that answered 404 followed by a GET that timed out reported the link as not confirmed; the 404 now stays. - A heading with an underscore inside a word (Pool_clearing) keeps it in its GitHub anchor. - A README HTML tag with a single-quoted href or src is read. - Without git on the PATH the script stops with a clear message (the files of the repository are the ones git tracks; the disk fallback ignored case on Windows). - The published site's address without its trailing slash is the site, not an external link. - The script requires PowerShell 7. Co-Authored-By: Claude Sonnet 5.5 --- docsite/tools/check-links.ps1 | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/docsite/tools/check-links.ps1 b/docsite/tools/check-links.ps1 index ba1d89ed..31d5098f 100644 --- a/docsite/tools/check-links.ps1 +++ b/docsite/tools/check-links.ps1 @@ -36,6 +36,7 @@ dotnet docfx docsite/docfx.json pwsh docsite/tools/check-links.ps1 #> +#Requires -Version 7.0 [CmdletBinding()] param( [string]$Site = (Join-Path $PSScriptRoot '..\_site'), @@ -84,7 +85,8 @@ function Get-MarkdownAnchors([string]$file) { foreach ($m in [regex]::Matches($text, '(?m)^ {0,3}#{1,6}[ \t]+(.+?)[ \t#]*$')) { $h = $m.Groups[1].Value $h = [regex]::Replace($h, '!?\[([^\]]*)\]\([^)]*\)', '$1') - $h = $h -replace '[`*_~]', '' + # Emphasis marks are dropped; an underscore between letters or digits is part of the word and stays. + $h = ($h -replace '[`*~]', '') -replace '(?$null) -if ($LASTEXITCODE -eq 0 -and $tracked.Count -gt 0) { - 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)) } - } +$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)) } } -else { $repoPaths = $null } # Resolves a path inside the site (no query, no fragment) to a file, or $null. function Resolve-SitePath([string]$path) { @@ -152,7 +154,7 @@ function Test-Link([string]$raw, [string]$source, [uri]$pageUri, [bool]$allowRel 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 = if ($relative.Trim('/') -eq '') { $true } elseif ($null -ne $repoPaths) { $repoPaths.Contains($relative.Trim('/')) } else { [System.IO.File]::Exists($local) -or [System.IO.Directory]::Exists($local) } + $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") } @@ -164,6 +166,8 @@ function Test-Link([string]$raw, [string]$source, [uri]$pageUri, [bool]$allowRel 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) { @@ -214,11 +218,13 @@ foreach ($md in $Markdown) { $text = [regex]::Replace($text, '(?ms)^[ \t]*(```|~~~).*?^[ \t]*\1', '') $text = [regex]::Replace($text, '`[^`\r\n]*`', '') $found = 0 - foreach ($m in [regex]::Matches($text, '!?\[[^\]]*\]\(\s*]|\([^()\s]*\))+)>?(?:\s+"[^"]*")?\s*\)')) { + # 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')) { - $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 @@ -257,7 +263,7 @@ else { $r = Invoke-WebRequest -Uri $url -Method Get -SkipHttpErrorCheck -TimeoutSec 10 -MaximumRedirection 8 -UserAgent 'docs-link-check' -ErrorAction Stop $status = [int]$r.StatusCode } - catch { $status = 0; $note = $_.Exception.Message } + 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 }