-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmkdocs_hooks.py
More file actions
62 lines (52 loc) · 2.4 KB
/
Copy pathmkdocs_hooks.py
File metadata and controls
62 lines (52 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""MkDocs build hooks."""
from __future__ import annotations
import logging
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
def on_config(config: Any, **kwargs: Any) -> Any:
# The i18n plugin renders every mkdocstrings symbol once per locale
# (e.g. /api/ and /en/api/), so mkdocs-autorefs reports each as having
# "Multiple primary URLs". That is expected for a bilingual site and not
# actionable, but it would otherwise abort `mkdocs build --strict`.
# Silence only that logger; every other warning still fails strict mode.
logging.getLogger("mkdocs.plugins.mkdocs_autorefs").setLevel(logging.ERROR)
return config
def on_post_build(config: Any, **kwargs: Any) -> None:
"""Emit a simplified fallback sitemap at ``pages.xml``.
The standard ``sitemap.xml`` generated by mkdocs-static-i18n includes
``xhtml:link`` alternates for the bilingual setup. Google Search Console
sometimes fails to fetch that sitemap on GitHub Pages (cached failure,
hreflang quirks). This hook produces a second, plain ``urlset`` sitemap
under a different filename so the GSC can be re-submitted without
hitting its failure cache.
"""
site_dir = Path(config["site_dir"])
src = site_dir / "sitemap.xml"
if not src.exists():
return
ns = {"s": "http://www.sitemaps.org/schemas/sitemap/0.9"}
# We're parsing the sitemap mkdocs itself just wrote on this same machine,
# not untrusted input — XXE is not a concern here.
tree = ET.parse(src) # noqa: S314
root = tree.getroot()
lines = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
]
for url in root.findall("s:url", ns):
loc = url.find("s:loc", ns)
lastmod = url.find("s:lastmod", ns)
changefreq = url.find("s:changefreq", ns)
if loc is None or loc.text is None:
continue
lines.append(" <url>")
lines.append(f" <loc>{loc.text}</loc>")
if lastmod is not None and lastmod.text:
lines.append(f" <lastmod>{lastmod.text}</lastmod>")
if changefreq is not None and changefreq.text:
lines.append(f" <changefreq>{changefreq.text}</changefreq>")
lines.append(" </url>")
lines.append("</urlset>")
out = site_dir / "pages.xml"
out.write_text("\n".join(lines) + "\n", encoding="utf-8")