Skip to content

Commit 987edb9

Browse files
committed
docs: fix relative links in github pages
1 parent a1fb579 commit 987edb9

File tree

4 files changed

+60
-30
lines changed

4 files changed

+60
-30
lines changed

docs/scripts/autorefs/plugin.py

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,16 @@
1616
this plugin searches for references of the form `[identifier][]` or `[title][identifier]` that were not resolved,
1717
and fixes them using the previously stored identifier-URL mapping.
1818
"""
19-
2019
import contextlib
2120
import functools
2221
import logging
22+
import os
2323
import re
2424
from html import escape, unescape
2525
from typing import Any, Callable, Dict, List, Match, Optional, Sequence, Tuple, Union
2626
from urllib.parse import urlsplit
2727
from xml.etree.ElementTree import Element
2828

29-
import pathspec
3029
from markdown import Markdown
3130
from markdown.extensions import Extension
3231
from markdown.inlinepatterns import REFERENCE_RE, ReferenceInlineProcessor
@@ -278,35 +277,37 @@ def __init__(self) -> None:
278277
def priority_patterns(self):
279278
if self._priority_patterns is None:
280279
self._priority_patterns = [
281-
pathspec.patterns.GitWildMatchPattern(pat)
282-
for pat in self.config.get("priority")
280+
os.path.join("/", pat) for pat in self.config.get("priority")
283281
]
284282
return self._priority_patterns
285283

286-
def register_anchor(self, page: str, identifier: str):
284+
def register_anchor(self, url: str, identifier: str):
287285
"""Register that an anchor corresponding to an identifier was encountered when rendering the page.
288286
289287
Arguments:
290-
page: The relative URL of the current page. Examples: `'foo/bar/'`, `'foo/index.html'`
288+
url: The relative URL of the current page. Examples: `'foo/bar/'`, `'foo/index.html'`
291289
identifier: The HTML anchor (without '#') as a string.
292290
"""
293-
if identifier in self._url_map:
291+
292+
new_url = os.path.join("/", f"{url}#{identifier}")
293+
old_url = os.path.join("/", self._url_map.get(identifier, "")).split("#")[0]
294+
295+
if identifier in self._url_map and not old_url == new_url:
294296
rev_patterns = list(enumerate(self.priority_patterns))[::-1]
295297
old_priority_idx = next(
296-
(
297-
i
298-
for i, pat in rev_patterns
299-
if pat.match_file(self._url_map[identifier])
300-
),
298+
(i for i, pat in rev_patterns if re.match(pat, old_url)),
301299
len(rev_patterns),
302300
)
303301
new_priority_idx = next(
304-
(i for i, pat in rev_patterns if pat.match_file(page)),
302+
(i for i, pat in rev_patterns if re.match(pat, new_url)),
305303
len(rev_patterns),
306304
)
307305
if new_priority_idx >= old_priority_idx:
308306
return
309-
self._url_map[identifier] = f"{page}#{identifier}"
307+
if "reference" not in new_url:
308+
raise Exception("URL WTF", new_url)
309+
310+
self._url_map[identifier] = new_url
310311

311312
def register_url(self, identifier: str, url: str):
312313
"""Register that the identifier should be turned into a link to this URL.
@@ -352,12 +353,7 @@ def get_item_url( # noqa: WPS234
352353
Returns:
353354
A site-relative URL.
354355
"""
355-
url = self._get_item_url(identifier, fallback)
356-
if from_url is not None:
357-
parsed = urlsplit(url)
358-
if not parsed.scheme and not parsed.netloc:
359-
return relative_url(from_url, url)
360-
return url
356+
return self._get_item_url(identifier, fallback)
361357

362358
def on_config(
363359
self, config: Config, **kwargs
@@ -418,10 +414,10 @@ def on_page_content(
418414
f"{__name__}: Mapping identifiers to URLs for page {page.file.src_path}"
419415
)
420416
for item in page.toc.items:
421-
self.map_urls(page.url, item)
417+
self.map_urls(page, item)
422418
return html
423419

424-
def map_urls(self, base_url: str, anchor: AnchorLink) -> None:
420+
def map_urls(self, page: Page, anchor: AnchorLink) -> None:
425421
"""Recurse on every anchor to map its ID to its absolute URL.
426422
427423
This method populates `self.url_map` by side-effect.
@@ -430,9 +426,10 @@ def map_urls(self, base_url: str, anchor: AnchorLink) -> None:
430426
base_url: The base URL to use as a prefix for each anchor's relative URL.
431427
anchor: The anchor to process and to recurse on.
432428
"""
433-
self.register_anchor(base_url, anchor.id)
429+
abs_url = os.path.join("/", page.file.url)
430+
self.register_anchor(abs_url, anchor.id)
434431
for child in anchor.children:
435-
self.map_urls(base_url, child)
432+
self.map_urls(page, child)
436433

437434
def on_post_page(
438435
self, output: str, page: Page, **kwargs

docs/scripts/griffe_ext.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,24 @@
11
import ast
22
import importlib
33
import inspect
4+
import logging
45
import sys
56
from typing import Union
67

78
import astunparse
8-
from griffe import Extension, Object, ObjectNode, get_logger
9+
from griffe import Extension, Object, ObjectNode
910
from griffe.docstrings.dataclasses import DocstringSectionParameters
11+
from griffe.expressions import Expr
12+
from griffe.logger import patch_loggers
13+
14+
15+
def get_logger(name):
16+
new_logger = logging.getLogger(name)
17+
new_logger.setLevel("ERROR")
18+
return new_logger
19+
20+
21+
patch_loggers(get_logger)
1022

1123
logger = get_logger(__name__)
1224

@@ -98,5 +110,7 @@ def on_instance(self, node: Union[ast.AST, ObjectNode], obj: Object) -> None:
98110
for param in param_section.value:
99111
if param.name in defaults:
100112
param.default = str(defaults[param.name])
113+
if isinstance(param.default, Expr):
114+
continue
101115
if param.default is not None and len(param.default) > 50:
102116
param.default = param.default[: 50 - 3] + "..."

docs/scripts/plugin.py

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
import mkdocs.structure.files
99
import mkdocs.structure.nav
1010
import mkdocs.structure.pages
11+
from mkdocs.config.defaults import MkDocsConfig
12+
13+
from docs.scripts.autorefs.plugin import AutorefsPlugin
1114

1215

1316
def exclude_file(name):
@@ -25,6 +28,23 @@ def exclude_file(name):
2528
"""
2629

2730

31+
@mkdocs.plugins.event_priority(1000)
32+
def on_config(config: MkDocsConfig):
33+
for event_name, events in config.plugins.events.items():
34+
for event in list(events):
35+
if "autorefs" in str(event):
36+
print("REMOVING EVENT", event_name, event)
37+
events.remove(event)
38+
old_plugin = config["plugins"]["autorefs"]
39+
plugin_config = dict(old_plugin.config)
40+
print("OLD PLUGIN CLASS:", type(old_plugin))
41+
plugin = AutorefsPlugin()
42+
print("NEW PLUGIN CLASS:", type(plugin))
43+
config.plugins["autorefs"] = plugin
44+
config["plugins"]["autorefs"] = plugin
45+
plugin.load_config(plugin_config)
46+
47+
2848
def on_files(files: mkdocs.structure.files.Files, config: mkdocs.config.Config):
2949
"""
3050
Recursively the navigation of the mkdocs config
@@ -124,11 +144,10 @@ def on_page_read_source(page, config):
124144

125145

126146
@mkdocs.plugins.event_priority(-1000)
127-
def on_page_content(
128-
html: str,
147+
def on_post_page(
148+
output: str,
129149
page: mkdocs.structure.pages.Page,
130150
config: mkdocs.config.Config,
131-
files: mkdocs.structure.files.Files,
132151
):
133152
def replace_link(match):
134153
relative_url = url = match.group(1)
@@ -138,4 +157,4 @@ def replace_link(match):
138157
return f'href="{relative_url}"'
139158

140159
# Replace absolute paths with path relative to the rendered page
141-
return re.sub(r'href="([^"]*)"', replace_link, html)
160+
return re.sub(r'href="([^"]*)"', replace_link, output)

mkdocs.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ plugins:
173173
- search
174174
- autorefs:
175175
priority:
176-
- '*'
176+
- .*
177177
- reference
178178
- mkdocstrings:
179179
enable_inventory: true

0 commit comments

Comments
 (0)