Skip to content
Snippets Groups Projects
Commit be2ea45a authored by Artur Sabirov's avatar Artur Sabirov
Browse files

feat: check svg attributes

parent 200e7c1b
No related branches found
No related tags found
1 merge request!315feat: check svg attributes
import os
import re
from urllib.parse import urlsplit
from mkdocs.plugins import get_plugin_logger
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import File, Files
from mkdocs.structure.pages import Page
from xml.dom import minidom
log = get_plugin_logger(os.path.basename(__file__))
# https://www.mkdocs.org/dev-guide/plugins/#events
def on_files(files: Files, config: MkDocsConfig):
for file in files.documentation_pages():
Page(None, file, config)
assert file.page is not None
file.page.read_source(config)
assert file.page.markdown is not None
markdown: str = file.page.markdown
lines: list[str] = re.sub("<!--.*?-->", "", markdown, flags=re.DOTALL).split("\n")
images: list[str] = list(filter(lambda line: re.match(r"^!\[", line), lines))
hrefs: list[str] = re.findall(r"(?<=\()(.*?\.svg)", " ".join(images))
hrefs = [hrefs[i][3:] for i in range(len(hrefs))]
for href in hrefs:
svg: File = Files.get_file_from_path(files, href) # type: ignore
dom = minidom.parse(svg.abs_src_path)
# Check `viewBox` attribute
for tag in dom.getElementsByTagName("svg"):
attr = tag.getAttribute("viewBox")
width = tag.getAttribute("width").replace("mm", "")
height = tag.getAttribute("height").replace("mm", "")
if not attr:
log.warning(f"MISSING viewBox @ {svg.src_path}")
continue
# Ensure values are equal to prevent image distortion
vals = attr.split()
if vals[2] != width:
log.warning(
f'DIFFER width="{width}" AND viewBox=". . {vals[2]} ." @ {svg.src_path}'
)
if vals[3] != height:
log.warning(
f'DIFFER height="{height}" AND viewBox=". . . {vals[3]}" @ {svg.src_path}'
)
# Check `xlink:href` attribute
for tag in dom.getElementsByTagName("a"):
attr = tag.getAttribute("xlink:href")
url = urlsplit(attr)
if url.path:
path = os.path.join(file.src_path, url.path)
path = f"{os.path.normpath(path)}.md"
else:
path = file.src_path
if path not in config["anchors"]:
log.warning(f"PAGE NOT FOUND @ {svg.src_path}: {path}")
continue
if url.fragment not in config["anchors"][path]:
log.warning(f"BROKEN ANCHOR @ {svg.src_path}: #{url.fragment}")
continue
# Drop loaded page in order to suppress MkDocs DeprecationWarning:
# "A plugin has set File.page to an instance of Page and it got overwritten.
# The behavior of this will change in MkDocs 1.6."
file.page = None
...@@ -159,4 +159,5 @@ validation: ...@@ -159,4 +159,5 @@ validation:
hooks: hooks:
- ./hooks/filter_logs.py - ./hooks/filter_logs.py
- ./hooks/check_headers.py - ./hooks/check_headers.py
- ./hooks/check_svg_attrs.py
- ./hooks/check_links.py - ./hooks/check_links.py
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment