# Copyright Kevin Deldycke <[email protected]> and contributors.
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""Every Markdown link to a heading also resolves on GitHub.
`docs/conf.py` points `myst_heading_slug_func` at docutils' `make_id`, so a
link written `unsupported.md#paq` is right on the published site. GitHub slugs
the rendered text of the same heading instead, and keeps what `make_id` drops:
the hyphen of each space around a glyph, and the variation selector after a
glyph like `☠`. A link to a title that ends in a verdict glyph thus finds no
anchor when the page is read on GitHub.
Neither reader can be dropped, so a heading whose two slugs disagree carries an
`<a name="{anchor}">` companion with the `make_id` spelling. That HTML anchor
renders no `id` on the site, where each section keeps the one id Sphinx gives
it.
A link to an anchor that only the build creates is out of scope, like the
command sections `{click:tree}` renders on `docs/cli-parameters.md`. No reader
of the raw Markdown can follow it, and the build fails on a broken one.
"""
from __future__ import annotations
import os
import re
import unicodedata
from pathlib import Path
import pytest
from meta_package_manager import _docs
from .conftest import PROJECT_ROOT
MARKDOWN_FILES = (
*sorted(PROJECT_ROOT.glob("*.md")),
*sorted((PROJECT_ROOT / "docs").glob("*.md")),
)
"""The pages a reader browses on GitHub."""
FENCE_OPEN = re.compile(r"^ {0,3}(?P<marker>`{3,}|~{3,})(?P<info>.*)$")
FENCE_CLOSE = re.compile(r"^ {0,3}(?P<marker>`{3,}|~{3,})\s*$")
"""A fence closes on its own marker character, repeated at least as many times
as it opened with, and followed by nothing."""
ATX_HEADING = re.compile(r"^#{1,6} +(?P<text>.+?)\s*$")
MYST_LABEL = re.compile(r"^\((?P<label>[^)\s]+)\)=\s*$")
HTML_ANCHOR = re.compile(r"""<a\s[^>]*\b(?:name|id)\s*=\s*["'](?P<anchor>[^"']+)["']""")
"""`<a name="x">` and `<a id="x">`, the two anchor forms GitHub resolves."""
FRAGMENT_LINK = re.compile(r"]\((?P<page>[^()\s#]*)#(?P<fragment>[^()\s]+)\)")
"""An inline link whose target carries a fragment: `](page.md#x)` or `](#x)`."""
INLINE_CODE = re.compile(r"(?<!`)(?P<ticks>`+)(?!`).+?(?<!`)(?P=ticks)(?!`)")
"""A code span, which holds no link and no anchor for a Markdown reader."""
INLINE_LINK = re.compile(r"\[(?P<text>[^\]]*)\]\([^)]*\)")
OCTICON = re.compile(r"\{octicon\}`[^`]*`")
"""An octicon role, which renders an icon and no text on the site."""
[docs]
def uncoded_lines(path: Path) -> list[tuple[int, str]]:
"""Number and return the lines of a page that sit outside a code fence.
GitHub renders a MyST directive fence like `{note}` as a code block, so a
link or a heading inside one is text for a reader there.
"""
lines = []
opening = ""
for number, line in enumerate(path.read_text(encoding="UTF-8").splitlines(), 1):
if opening:
close = FENCE_CLOSE.match(line)
if (
close
and close["marker"][0] == opening[0]
and len(close["marker"]) >= len(opening)
):
opening = ""
continue
fence = FENCE_OPEN.match(line)
# The info string of a backtick fence holds no backtick, which keeps an
# inline code span like ``x`` from opening a block.
if fence and not (fence["marker"][0] == "`" and "`" in fence["info"]):
opening = fence["marker"]
continue
lines.append((number, line))
return lines
[docs]
def github_slug(heading: str) -> str:
"""Slug a heading the way GitHub does.
GitHub slugs the rendered text, so a link keeps its text and a code span its
content. It lowercases that text and drops each character that is not a
letter, a mark, a decimal digit, an underscore, a hyphen or a space. Then it
writes a hyphen for each space.
"""
text = INLINE_LINK.sub(r"\g<text>", heading).replace("`", "").lower()
return "".join(
char
for char in text
if char in "-_ "
or unicodedata.category(char)[0] in "LM"
or unicodedata.category(char) == "Nd"
).replace(" ", "-")
[docs]
def site_slug(heading: str) -> str:
"""Slug a heading the way the site does, with docutils' `make_id`."""
return _docs._heading_slug(OCTICON.sub("", heading))
[docs]
def github_anchors(path: Path) -> set[str]:
"""Collect every fragment GitHub resolves on a page.
A repeated slug gets the suffix GitHub gives it: `-1` for the second
heading, `-2` for the third.
"""
anchors = set()
seen: dict[str, int] = {}
for _number, line in uncoded_lines(path):
anchors.update(HTML_ANCHOR.findall(INLINE_CODE.sub("", line)))
heading = ATX_HEADING.match(line)
if heading:
slug = github_slug(heading["text"])
count = seen.get(slug, 0)
seen[slug] = count + 1
anchors.add(f"{slug}-{count}" if count else slug)
return anchors
[docs]
def site_anchors(path: Path) -> set[str]:
"""Collect the anchors the site gives to the headings and labels of a page."""
anchors = set()
for _number, line in uncoded_lines(path):
heading = ATX_HEADING.match(line)
if heading:
anchors.add(site_slug(heading["text"]))
label = MYST_LABEL.match(line)
if label:
anchors.add(label["label"])
return anchors
[docs]
def unreadable_heading_links(
paths: tuple[Path, ...] = MARKDOWN_FILES, root: Path = PROJECT_ROOT
) -> list[str]:
"""Report each link to a heading or a label that GitHub cannot follow.
Each entry names the line of the link and its target, so a failure says
which heading needs a companion.
"""
readable: dict[Path, set[str]] = {}
written: dict[Path, set[str]] = {}
misses = []
for path in paths:
for number, line in uncoded_lines(path):
for link in FRAGMENT_LINK.finditer(INLINE_CODE.sub("", line)):
page, fragment = link["page"], link["fragment"]
target = Path(os.path.normpath(path.parent / page)) if page else path
# A URL or an asset carries no heading of this repository.
if target.suffix != ".md" or not target.is_file():
continue
if target not in readable:
readable[target] = github_anchors(target)
written[target] = site_anchors(target)
if fragment in written[target] and fragment not in readable[target]:
misses.append(
f"{path.relative_to(root)}:{number} -> "
f"{target.relative_to(root)}#{fragment}"
)
return misses
[docs]
def test_markdown_files_are_collected():
"""The glob feeding the check still finds the documentation."""
assert len(MARKDOWN_FILES) > 40, "documentation pages went missing"
[docs]
def test_heading_links_resolve_on_github():
"""No link to a heading dangles when the page is read on GitHub.
A failure names a heading that GitHub slugs differently from `make_id`. Add
an `<a name="{fragment}"></a>` line and a blank line above that heading,
rather than rewording the link: the site renders the `make_id` spelling.
"""
misses = unreadable_heading_links()
assert not misses, "links GitHub cannot follow:\n " + "\n ".join(misses)
[docs]
@pytest.mark.parametrize(
("heading", "github", "site"),
(
(
"[`app-man`](https://github.com/ivan-hc/AppMan) ❌ 🛟",
"app-man--",
"app-man",
),
("Container runtimes ❌ 🛟", "container-runtimes--", "container-runtimes"),
(
"[`ares-install`](https://github.com/webos-tools/cli) ❌",
"ares-install-",
"ares-install",
),
(
"{octicon}`circle-slash` Unsupported managers",
"octiconcircle-slash-unsupported-managers",
"unsupported-managers",
),
("Ubuntu (PPA)", "ubuntu-ppa", "ubuntu-ppa"),
),
)
def test_slugs(heading, github, site):
"""Both slug functions give the anchors of real headings of the docs."""
assert github_slug(heading) == github
assert site_slug(heading) == site
[docs]
def test_links_to_build_time_anchors_are_skipped(tmp_path):
"""Only a link to a written heading is checked, and a companion answers it."""
pond = tmp_path / "pond.md"
pond.write_text(
"# Pond\n\n"
"## Frogs ❌\n\n"
'<a name="lilies"></a>\n\n'
"## Lilies ❌\n\n"
"```{note}\n## Herons ❌\n```\n",
encoding="UTF-8",
)
walk = tmp_path / "walk.md"
walk.write_text(
"See [the frogs](pond.md#frogs), [the lilies](pond.md#lilies),\n"
"[the herons](pond.md#herons), [the ducks](pond.md#ducks) and\n"
"`[the reeds](pond.md#frogs)`.\n",
encoding="UTF-8",
)
assert unreadable_heading_links((walk,), tmp_path) == ["walk.md:1 -> pond.md#frogs"]