Skip to content

Commit

Permalink
feat: add config for auto_links
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilkrzyskow committed Nov 2, 2024
1 parent 03c7dc4 commit 2fd5d1e
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 5 deletions.
79 changes: 78 additions & 1 deletion mkdocs_nype/plugins/custom_auto_links/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,82 @@
from mkdocs.config import Config
from mkdocs.config.base import ConfigErrors, ConfigWarnings, ValidationError
from mkdocs.config.config_options import DictOfItems, ListOfItems, SubConfig, Type

SUPPORTED_PROTOCOLS = ("fal",)
"""Tuple of supported protocols"""


class FalProtocolExtras(Config):

load_presets = Type(bool, default=True)
"""Load preset values like the releases"""

releases_map = DictOfItems(Type((int, str)), default={})
"""Extra releases"""

tags_map = DictOfItems(Type((int, str)), default={})
"""Extra tag handling"""

fallback_id = Type((int, str), default="")
"""Fallback release id to use when not set in URL / tags"""

def validate(self):
failed, warnings = super().validate()

def convert_values_to_str(mapping):
for key, value in mapping.items():
if isinstance(value, int):
mapping[key] = str(value)

convert_values_to_str(self.releases_map)
convert_values_to_str(self.tags_map)

if isinstance(self.fallback_id, int):
self.fallback_id = str(self.fallback_id)

return failed, warnings


class CustomAutoLinksConfig(Config):
pass

fal = SubConfig(FalProtocolExtras, validate=True)
"""fal protocol extras"""


# This code was never used but works. Allows for runtime creation of the config schema.
# Doesn't autocomplete because of the runtime creation, so not practical for this use case.
#
# def extend_config(config: CustomAutoLinksConfig) -> CustomAutoLinksConfig:
# protocol_extras = {
# "fal": {
# "load_presets": Type(bool, default=True),
# "fallback_id": Type(str, default=""),
# "releases": DictOfItems(Type(str), default={}),
# }
# }
# """Template for the allowed protocol extras with their types"""

# for name in protocol_extras:
# if name not in SUPPORTED_PROTOCOLS:
# raise ValidationError(f"Protocol not supported {name}")

# # Extend the class dynamically with new attributes
# for protocol, extras in protocol_extras.items():

# if not extras:
# continue

# class ProtocolConfig(Config):
# pass

# for name, value in extras.items():
# setattr(ProtocolConfig, name, value)

# # Subclass needs to init again to go over the new attributes
# ProtocolConfig.__init_subclass__()
# setattr(config, protocol, SubConfig(ProtocolConfig, validate=True))

# # Subclass needs to init again to go over the new attributes
# config.__init_subclass__()

# return config
34 changes: 31 additions & 3 deletions mkdocs_nype/plugins/custom_auto_links/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,19 @@ def __init__(self) -> None:
pattern=r'(?P<prefix>\s|\]\(|")(?P<proto>fal)://(?P<mode>\w!)?(?P<url>.*?)(?=\s|\)|")',
flags=re.IGNORECASE | re.MULTILINE,
)
self.fal_releases = {}

def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:

# Clear the dict between mkdocs serve runs
self.fal_releases.clear()

# Set up fal config
if self.config.fal.load_presets:
self.fal_releases.update(FAL_RELEASE_MAPPING)

if self.config.fal.releases_map:
self.fal_releases.update(self.config.fal.releases_map)

@event_priority(100)
def on_page_markdown(
Expand Down Expand Up @@ -61,29 +74,44 @@ def _process_fal(self, match: re.Match, page: Page) -> etree.Element:
url_no_params, *params = url.split("?")
product_id, *md_release_id = url_no_params.rstrip("/").split("/")

# fal://F1234/1998_FPS01/SomethingElse not allowed
if len(md_release_id) > 1:
raise ValueError(
f"Too many '/' in the {match}, {md_release_id=}\nFile: {page.file.src_uri}"
)

# 1998_FPS01 from fal://F1234/1998_FPS01 will be used
if md_release_id:
short_release_id = md_release_id[0]
# Extract the release_id from the tags in the file
else:
short_release_id = None
meta_tags = page.meta.get("tags") or []
for tag in meta_tags:
if tag.startswith("SAP S/4HANA"):
for pattern, rid in self.config.fal.tags_map.items():
if re.match(pattern, tag, flags=re.IGNORECASE):
short_release_id = rid
break

if short_release_id:
break

if tag.startswith("SAP S/4HANA") and tag != "SAP S/4HANA":
short_release_id = tag.replace("SAP S/4HANA", "", 1).strip().replace(" ", "_")
break

if not short_release_id:
# Nothing found in the URL or the tags, use fallback
if not short_release_id and self.config.fal.fallback_id:
short_release_id = self.config.fal.fallback_id
# No fallback, can't progress, raise error
elif not short_release_id:
raise RuntimeError(
f"Could not find short_release_id for the {match}"
"\nThe issue could be a lack of 'tags' or a typo"
f"\nFile: {page.file.src_uri}"
)

fal_release = FAL_RELEASE_MAPPING[short_release_id]
fal_release = self.fal_releases[short_release_id]
href = f"https://fioriappslibrary.hana.ondemand.com/sap/fix/externalViewer/#/detail/Apps(%27{product_id}%27)/{fal_release}"

el = etree.Element("a")
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ build-backend = "hatchling.build"

[project]
name = "mkdocs-nype"
version = "0.19.0"
version = "0.20.0"
description = "MkDocs theme for Nype MkDocs projects, extends the Material for MkDocs theme"
authors = [
{ name = "Kamil Krzyśków", email = "[email protected]" }
Expand Down

0 comments on commit 2fd5d1e

Please sign in to comment.