mkdocs-mknodes 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. mkdocs_mknodes/__init__.py +1 -0
  2. mkdocs_mknodes/buildcollector.py +167 -0
  3. mkdocs_mknodes/cli/__init__.py +194 -0
  4. mkdocs_mknodes/manual/__init__.py +13 -0
  5. mkdocs_mknodes/manual/cli_section.py +37 -0
  6. mkdocs_mknodes/manual/dev_section.py +70 -0
  7. mkdocs_mknodes/manual/github_index.py +17 -0
  8. mkdocs_mknodes/manual/internals_section.py +74 -0
  9. mkdocs_mknodes/manual/multi_project.py +19 -0
  10. mkdocs_mknodes/manual/root.py +77 -0
  11. mkdocs_mknodes/manual/use_cases_section.py +34 -0
  12. mkdocs_mknodes/mkdocsconfig.py +141 -0
  13. mkdocs_mknodes/paths.py +11 -0
  14. mkdocs_mknodes/plugin/__init__.py +179 -0
  15. mkdocs_mknodes/plugin/build_page.py +165 -0
  16. mkdocs_mknodes/plugin/buildbackend.py +45 -0
  17. mkdocs_mknodes/plugin/linkreplacer.py +49 -0
  18. mkdocs_mknodes/plugin/markdownbackend.py +37 -0
  19. mkdocs_mknodes/plugin/mkdocsbackend.py +184 -0
  20. mkdocs_mknodes/plugin/mkdocsbuilder.py +127 -0
  21. mkdocs_mknodes/plugin/mkdocshelpers.py +24 -0
  22. mkdocs_mknodes/plugin/pluginconfig.py +45 -0
  23. mkdocs_mknodes/plugin/serve.py +228 -0
  24. mkdocs_mknodes/resources/build_process.jinja +55 -0
  25. mkdocs_mknodes/resources/cli_index.jinja +15 -0
  26. mkdocs_mknodes/resources/material_css.jinja +88 -0
  27. mkdocs_mknodes/resources/material_css_extra.jinja +223 -0
  28. mkdocs_mknodes/resources/mkclasspage.jinja +11 -0
  29. mkdocs_mknodes/resources/mkdocs_css.jinja +7 -0
  30. mkdocs_mknodes/resources/modulepage.md +11 -0
  31. mkdocs_mknodes/resources/python_objects.inv +0 -0
  32. mkdocs_mknodes/resources/requirements.md +31 -0
  33. mkdocs_mknodes/resources/use_case_by_config.jinja +10 -0
  34. mkdocs_mknodes/resources/use_case_default_website.jinja +10 -0
  35. mkdocs_mknodes/resources/use_cases_index.jinja +46 -0
  36. mkdocs_mknodes-0.0.2.dist-info/METADATA +96 -0
  37. mkdocs_mknodes-0.0.2.dist-info/RECORD +40 -0
  38. mkdocs_mknodes-0.0.2.dist-info/WHEEL +4 -0
  39. mkdocs_mknodes-0.0.2.dist-info/entry_points.txt +5 -0
  40. mkdocs_mknodes-0.0.2.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,34 @@
1
+ import mknodes as mk
2
+
3
+ from mknodes.info import mkdocsconfigfile
4
+
5
+
6
+ nav = mk.MkNav("Use cases")
7
+
8
+
9
+ def create_use_cases_section(root_nav: mk.MkNav):
10
+ """Create the "Development" sub-MkNav."""
11
+ root_nav += nav
12
+ page = nav.add_index_page(hide="toc")
13
+ page += mk.MkJinjaTemplate("use_cases_index.jinja")
14
+ page.created_by = create_use_cases_section
15
+
16
+
17
+ @nav.route.page("Creating a sample website", hide="toc")
18
+ def create_default_website_section(page: mk.MkPage):
19
+ """Create the "Creating a sample website" MkPage."""
20
+ file = mkdocsconfigfile.MkDocsConfigFile("configs/mkdocs_mkdocs.yml")
21
+ section = file.get_section("plugins", "mknodes", keep_path=True)
22
+ config = section.serialize("yaml")
23
+ variables = dict(config=config)
24
+ page += mk.MkJinjaTemplate("use_case_default_website.jinja", variables=variables)
25
+
26
+
27
+ @nav.route.page("Creating a website via config", hide="toc")
28
+ def create_custom_website_by_config(page: mk.MkPage):
29
+ """Create the "Creating a sample website via config" MkPage."""
30
+ file = mkdocsconfigfile.MkDocsConfigFile("configs/mkdocs_mkdocstrings.yml")
31
+ section = file.get_section("plugins", "mknodes", keep_path=True)
32
+ config = section.serialize("yaml")
33
+ variables = dict(config=config)
34
+ page += mk.MkJinjaTemplate("use_case_by_config.jinja", variables=variables)
@@ -0,0 +1,141 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ import contextlib
5
+ import functools
6
+ import io
7
+ import os
8
+ import pathlib
9
+
10
+ from typing import Any
11
+ from urllib import parse
12
+
13
+ from mkdocs import config as _config
14
+ from mkdocs.commands import get_deps
15
+ from mkdocs.config.defaults import MkDocsConfig
16
+ from mkdocs.plugins import get_plugin_logger
17
+ from mknodes.info import contexts
18
+ from mknodes.utils import mdconverter, pathhelpers
19
+
20
+
21
+ logger = get_plugin_logger(__name__)
22
+
23
+
24
+ @functools.cache
25
+ def load_config(path: str | os.PathLike | None = None) -> MkDocsConfig:
26
+ path = None if path is None else str(path)
27
+ cfg = _config.load_config(path)
28
+ logger.info("Loaded config from path '%s'", path or "mkdocs.yml")
29
+ return cfg
30
+
31
+
32
+ class Config:
33
+ def __init__(self, config: Mapping | str | os.PathLike | None = None):
34
+ match config:
35
+ case MkDocsConfig():
36
+ self._config: MkDocsConfig = config
37
+ case Mapping():
38
+ self._config = load_config(config)
39
+ case str() | os.PathLike() as path:
40
+ self._config = load_config(str(path))
41
+ case None:
42
+ if file := pathhelpers.find_file_in_folder_or_parent("mkdocs.yml"):
43
+ self._config = load_config(str(file))
44
+ else:
45
+ msg = "Could not find config file"
46
+ raise FileNotFoundError(msg)
47
+ case _:
48
+ raise TypeError(config)
49
+ self.plugin = self._config.plugins["mknodes"]
50
+
51
+ def __getattr__(self, name):
52
+ return getattr(self._config, name)
53
+
54
+ @property
55
+ def site_url(self) -> str:
56
+ url = self._config.site_url
57
+ if url is None:
58
+ return ""
59
+ return url if url.endswith("/") else f"{url}/"
60
+
61
+ @property
62
+ def docs_dir(self) -> pathlib.Path:
63
+ return pathlib.Path(self._config.docs_dir)
64
+
65
+ @property
66
+ def site_dir(self) -> pathlib.Path:
67
+ return pathlib.Path(self._config.site_dir)
68
+
69
+ def update_from_context(self, context: contexts.ProjectContext):
70
+ if not self._config.extra.get("social"):
71
+ self._config.extra["social"] = context.metadata.social_info
72
+ self._config.repo_url = context.metadata.repository_url
73
+ self._config.site_description = context.metadata.summary
74
+ self._config.site_name = context.metadata.distribution_name
75
+ self._config.site_author = context.metadata.author_name
76
+
77
+ def get_markdown_instance(
78
+ self,
79
+ additional_extensions: list[str] | None = None,
80
+ config_override: dict[str, Any] | None = None,
81
+ ) -> mdconverter.MdConverter:
82
+ """Return a markdown instance based on given config."""
83
+ extensions = self._config.markdown_extensions
84
+ if additional_extensions:
85
+ extensions = list(set(additional_extensions + extensions))
86
+ configs = self._config.mdx_configs | (config_override or {})
87
+ return mdconverter.MdConverter(extensions=extensions, extension_configs=configs)
88
+
89
+ def get_edit_url(self, edit_path: str | None) -> str | None:
90
+ repo_url = self.repo_url
91
+ if not repo_url:
92
+ return None
93
+ edit_uri = self.edit_uri or "edit/main/"
94
+ if not edit_uri.startswith(("?", "#")) and not repo_url.endswith("/"):
95
+ repo_url += "/"
96
+ rel_path = self.plugin.config.build_fn.split(":")[0]
97
+ if not rel_path.endswith(".py"):
98
+ rel_path = rel_path.replace(".", "/")
99
+ rel_path += ".py"
100
+ base_url = parse.urljoin(repo_url, edit_uri)
101
+ if repo_url and edit_path:
102
+ # root_path = pathlib.Path(config["docs_dir"]).parent
103
+ # edit_path = str(edit_path.relative_to(root_path))
104
+ rel_path = edit_path
105
+ return parse.urljoin(base_url, rel_path)
106
+
107
+ def get_install_candidates(self) -> list[str]:
108
+ """Return a list of installation candidates for this config."""
109
+ path = "https://raw.githubusercontent.com/mkdocs/catalog/main/projects.yaml"
110
+ buffer = io.StringIO()
111
+ with contextlib.redirect_stdout(buffer):
112
+ get_deps.get_deps(path, self._config.config_file_path)
113
+ return [i for i in buffer.getvalue().split("\n") if i]
114
+
115
+ def add_js(
116
+ self,
117
+ path: str,
118
+ defer: bool = False,
119
+ async_: bool = False,
120
+ typ: str = "",
121
+ ):
122
+ """Add javascript to the config.
123
+
124
+ Arguments:
125
+ path: Path / URL to the javascript file
126
+ defer: Add defer attribute to <script> tag
127
+ async_: Add async attribute to <script> tag
128
+ typ: Add given type attribute to <script> tag
129
+ """
130
+ from mkdocs.config import config_options
131
+
132
+ val = config_options.ExtraScriptValue(str(path))
133
+ val.async_ = async_
134
+ val.defer = defer
135
+ val.type = typ
136
+ self.extra_javascript.append(val)
137
+
138
+
139
+ if __name__ == "__main__":
140
+ cfg = Config()
141
+ print(cfg.theme._vars)
@@ -0,0 +1,11 @@
1
+ from __future__ import annotations
2
+
3
+ import pathlib
4
+
5
+
6
+ CFG_DEFAULT = "configs/mkdocs_basic.yml"
7
+ TEST_RESOURCES = pathlib.Path(__file__).parent.parent / "tests" / "data"
8
+ RESOURCES = pathlib.Path(__file__).parent / "resources"
9
+ CSS_DIR = RESOURCES / "css"
10
+ DOCS_DIR = pathlib.Path(__file__).parent.parent / "docs"
11
+ DEFAULT_BUILD_FN = "mknodes.navs.mkdefaultwebsite:MkDefaultWebsite.for_project"
@@ -0,0 +1,179 @@
1
+ """The Mkdocs Plugin."""
2
+
3
+ from __future__ import annotations
4
+ from collections.abc import Callable
5
+
6
+ import pathlib
7
+ import urllib.parse
8
+
9
+ import tempfile
10
+ from typing import TYPE_CHECKING, Literal
11
+ from mkdocs import livereload
12
+
13
+ from mkdocs.plugins import BasePlugin, get_plugin_logger
14
+
15
+ from mknodes import buildcollector, mkdocsconfig, project
16
+ from mknodes.pages import mkpage
17
+ from mkdocs_mknodes.plugin import (
18
+ linkreplacer,
19
+ markdownbackend,
20
+ mkdocsbackend,
21
+ pluginconfig,
22
+ )
23
+ from mknodes.theme import theme
24
+
25
+ if TYPE_CHECKING:
26
+ import jinja2
27
+ from mkdocs.config.defaults import MkDocsConfig
28
+ from mkdocs.structure.files import Files
29
+ from mkdocs.structure.nav import Navigation
30
+ from mkdocs.structure.pages import Page
31
+
32
+ # from mkdocs.utils.templates import TemplateContext
33
+
34
+
35
+ logger = get_plugin_logger(__name__)
36
+
37
+ CommandStr = Literal["build", "serve", "gh-deploy"]
38
+
39
+
40
+ class MkNodesPlugin(BasePlugin[pluginconfig.PluginConfig]):
41
+ def __init__(self, **kwargs):
42
+ super().__init__(**kwargs)
43
+ self.link_replacer = linkreplacer.LinkReplacer()
44
+ logger.debug("Finished initializing plugin")
45
+
46
+ def on_startup(self, command: CommandStr, dirty: bool = False):
47
+ """Activates new-style MkDocs plugin lifecycle."""
48
+ if self.config.build_folder:
49
+ self.build_folder = pathlib.Path(self.config.build_folder)
50
+ else:
51
+ self._dir = tempfile.TemporaryDirectory(prefix="mknodes_")
52
+ self.build_folder = pathlib.Path(self._dir.name)
53
+ logger.debug("Creating temporary dir %s", self._dir.name)
54
+
55
+ def on_config(self, config: MkDocsConfig):
56
+ """Create the project based on MkDocs config."""
57
+ if not self.config.build_fn:
58
+ return
59
+ skin = theme.Theme.get_theme(
60
+ theme_name=config.theme.name or "material",
61
+ data=config.theme._vars, # type: ignore[attr-defined]
62
+ )
63
+ self.project = project.Project(
64
+ base_url=config.site_url or "",
65
+ use_directory_urls=config.use_directory_urls,
66
+ theme=skin,
67
+ repo=self.config.repo_path,
68
+ build_fn=self.config.build_fn,
69
+ build_kwargs=self.config.kwargs,
70
+ clone_depth=self.config.clone_depth,
71
+ )
72
+
73
+ def on_files(self, files: Files, config: MkDocsConfig) -> Files:
74
+ """Create the node tree and write files to build folder.
75
+
76
+ In this step we aggregate all files and info we need to build the website.
77
+ This includes:
78
+
79
+ - Markdown pages (MkPages)
80
+ - Templates
81
+ - CSS files
82
+ """
83
+ if not self.config.build_fn:
84
+ return files
85
+
86
+ logger.info("Generating pages...")
87
+ self.project.build()
88
+ # now we add our stuff to the MkDocs build environment
89
+ cfg = mkdocsconfig.Config(config)
90
+
91
+ logger.info("Updating MkDocs config metadata...")
92
+ cfg.update_from_context(self.project.context)
93
+
94
+ logger.info("Setting up build backends...")
95
+ mkdocs_backend = mkdocsbackend.MkDocsBackend(
96
+ files=files,
97
+ config=config,
98
+ directory=self.build_folder,
99
+ )
100
+
101
+ markdown_backend = markdownbackend.MarkdownBackend(
102
+ directory=pathlib.Path(config.site_dir) / "src",
103
+ extension=".original",
104
+ )
105
+ collector = buildcollector.BuildCollector(
106
+ backends=[mkdocs_backend, markdown_backend],
107
+ show_page_info=self.config.show_page_info,
108
+ )
109
+ assert self.project._root
110
+ self.build_info = collector.collect(self.project._root, self.project.theme)
111
+ return mkdocs_backend.files
112
+
113
+ def on_nav(
114
+ self,
115
+ nav: Navigation,
116
+ files: Files,
117
+ config: MkDocsConfig,
118
+ ) -> Navigation | None:
119
+ """Populate LinkReplacer and build path->MkPage mapping for following steps."""
120
+ for file_ in files:
121
+ filename = pathlib.Path(file_.abs_src_path).name
122
+ url = urllib.parse.unquote(file_.src_uri)
123
+ self.link_replacer.mapping[filename].append(url)
124
+ return nav
125
+
126
+ def on_env(self, env: jinja2.Environment, config: MkDocsConfig, files: Files):
127
+ """Add our own info to the MkDocs environment."""
128
+ node_env = self.project.context.env
129
+ env.globals["mknodes"] = node_env.globals
130
+ env.filters |= node_env.filters
131
+ logger.debug("Added macros / filters to MkDocs jinja2 environment.")
132
+
133
+ def on_pre_page(
134
+ self,
135
+ page: Page,
136
+ config: MkDocsConfig,
137
+ files: Files,
138
+ ) -> Page | None:
139
+ """During this phase we set the edit paths."""
140
+ node = self.build_info.page_mapping.get(page.file.src_uri)
141
+ edit_path = node._edit_path if isinstance(node, mkpage.MkPage) else None
142
+ cfg = mkdocsconfig.Config(config)
143
+ if path := cfg.get_edit_url(edit_path):
144
+ page.edit_url = path
145
+ return page
146
+
147
+ def on_page_markdown(
148
+ self,
149
+ markdown: str,
150
+ page: Page,
151
+ config: MkDocsConfig,
152
+ files: Files,
153
+ ) -> str | None:
154
+ """During this phase links get replaced and `jinja2` stuff get rendered."""
155
+ node = self.build_info.page_mapping.get(page.file.src_uri)
156
+ if node is None:
157
+ return markdown
158
+ markdown = node.env.render_string(markdown)
159
+ return self.link_replacer.replace(markdown, page.file.src_uri)
160
+
161
+ def on_post_build(self, config: MkDocsConfig):
162
+ """Delete the temporary template files."""
163
+ if not config.theme.custom_dir:
164
+ return
165
+ if not self.config.build_fn:
166
+ return
167
+ for template in self.build_info.resources.templates:
168
+ path = pathlib.Path(config.theme.custom_dir) / template.filename
169
+ path.unlink(missing_ok=True)
170
+
171
+ def on_serve(
172
+ self,
173
+ server: livereload.LiveReloadServer,
174
+ config: MkDocsConfig,
175
+ builder: Callable,
176
+ ):
177
+ """Remove all watched paths in case MkNodes is used to build the website."""
178
+ if self.config.build_fn:
179
+ server._watched_paths = {}
@@ -0,0 +1,165 @@
1
+ """The Mkdocs Plugin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ import io
7
+ import logging
8
+ import time
9
+
10
+ from typing import TYPE_CHECKING, Any
11
+ from urllib.parse import urljoin
12
+
13
+ from mkdocs import utils
14
+ from mkdocs.commands import build as mkdocs_build
15
+ from mkdocs.config import load_config
16
+ from mkdocs.exceptions import Abort, BuildError
17
+ from mkdocs.plugins import get_plugin_logger
18
+ from mkdocs.structure.files import InclusionLevel, _set_exclusions, get_files
19
+ from mkdocs.structure.nav import get_navigation
20
+ from mkdocs.structure.pages import Page
21
+ from mknodes.utils import yamlhelpers
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from mkdocs.config.defaults import MkDocsConfig
26
+
27
+
28
+ logger = get_plugin_logger(__name__)
29
+
30
+
31
+ def build(config: MkDocsConfig | Mapping[str, Any], **kwargs):
32
+ text = yamlhelpers.dump_yaml(dict(config))
33
+ buffer = io.StringIO(text)
34
+ config = load_config(buffer, **kwargs)
35
+ for k, v in config.items():
36
+ logger.debug("%s: %s", k, v)
37
+ config.plugins.run_event("startup", command="build", dirty=False)
38
+ _build(config)
39
+ config.plugins.run_event("shutdown")
40
+
41
+
42
+ def _build(
43
+ config: MkDocsConfig,
44
+ live_server_url: str | None = None,
45
+ dirty: bool = False,
46
+ ) -> None:
47
+ """Perform a full site build."""
48
+ # Add CountHandler for strict mode
49
+ warning_counter = utils.CountHandler()
50
+ warning_counter.setLevel(logging.WARNING)
51
+ if config.strict:
52
+ logging.getLogger("mkdocs").addHandler(warning_counter)
53
+
54
+ inclusion = InclusionLevel.all if live_server_url else InclusionLevel.is_included
55
+
56
+ try:
57
+ start = time.monotonic()
58
+ config = config.plugins.on_config(config)
59
+ config.plugins.on_pre_build(config=config)
60
+
61
+ if not dirty:
62
+ logger.info("Cleaning site directory")
63
+ utils.clean_directory(config.site_dir)
64
+ else: # pragma: no cover
65
+ logger.warning(
66
+ "A 'dirty' build is being performed, this will likely lead to inaccurate "
67
+ " navigation and other links within your site. "
68
+ "This option is designed for site development purposes only.",
69
+ )
70
+
71
+ if not live_server_url: # pragma: no cover
72
+ logger.info("Building documentation to directory: %s", config.site_dir)
73
+ if dirty and mkdocs_build.site_directory_contains_stale_files(
74
+ config.site_dir,
75
+ ):
76
+ logger.info(
77
+ "The directory contains stale files. Use --clean to remove them.",
78
+ )
79
+
80
+ # First gather all data from all files/pages to ensure all data is
81
+ # consistent across all pages.
82
+
83
+ files = get_files(config)
84
+ env = config.theme.get_env()
85
+ files.add_files_from_theme(env, config)
86
+ files = config.plugins.on_files(files, config=config)
87
+ # If plugins have added files without setting inclusion level, calculate it again.
88
+ _set_exclusions(files._files, config)
89
+
90
+ nav = get_navigation(files, config)
91
+
92
+ # Run `nav` plugin events.
93
+ nav = config.plugins.on_nav(nav, config=config, files=files)
94
+
95
+ logger.debug("Reading markdown pages.")
96
+ excluded = []
97
+ for file in files.documentation_pages(inclusion=inclusion):
98
+ logger.debug("Reading: %s", file.src_uri)
99
+ if file.page is None and file.inclusion.is_excluded():
100
+ if live_server_url:
101
+ excluded.append(urljoin(live_server_url, file.url))
102
+ Page(None, file, config)
103
+ assert file.page is not None
104
+ mkdocs_build._populate_page(file.page, config, files, dirty)
105
+ if excluded:
106
+ excluded_str = "\n - ".join(excluded)
107
+ logger.info(
108
+ "The following pages are being built only for the preview "
109
+ "but will be excluded from `mkdocs build` per `exclude_docs`:"
110
+ "\n - %s",
111
+ excluded_str,
112
+ )
113
+
114
+ # Run `env` plugin events.
115
+ env = config.plugins.on_env(env, config=config, files=files)
116
+
117
+ # Start writing files to site_dir now that all data is gathered.
118
+ # Note that order matters. Files with lower precedence get written first
119
+ # so that files with higher precedence can overwrite them.
120
+
121
+ logger.debug("Copying static assets.")
122
+ files.copy_static_files(dirty=dirty, inclusion=inclusion)
123
+
124
+ for template in config.theme.static_templates:
125
+ mkdocs_build._build_theme_template(template, env, files, config, nav)
126
+
127
+ for template in config.extra_templates:
128
+ mkdocs_build._build_extra_template(template, files, config, nav)
129
+
130
+ logger.debug("Building markdown pages.")
131
+ doc_files = files.documentation_pages(inclusion=inclusion)
132
+ for file in doc_files:
133
+ assert file.page is not None
134
+ mkdocs_build._build_page(
135
+ file.page,
136
+ config,
137
+ doc_files,
138
+ nav,
139
+ env,
140
+ dirty,
141
+ excluded=file.inclusion.is_excluded(),
142
+ )
143
+
144
+ # Run `post_build` plugin events.
145
+ config.plugins.on_post_build(config=config)
146
+
147
+ counts = warning_counter.get_counts()
148
+ if counts:
149
+ msg = ", ".join(f"{v} {k.lower()}s" for k, v in counts)
150
+ msg = f"Aborted with {msg} in strict mode!"
151
+ raise Abort(msg) # noqa: TRY301
152
+ duration = time.monotonic() - start
153
+ logger.info("Documentation built in %.2f seconds", duration)
154
+
155
+ except Exception as e:
156
+ # Run `build_error` plugin events.
157
+ config.plugins.on_build_error(error=e)
158
+ if isinstance(e, BuildError):
159
+ msg = "Aborted with a BuildError!"
160
+ logger.exception(msg)
161
+ raise Abort(msg) from e
162
+ raise
163
+
164
+ finally:
165
+ logging.getLogger("mkdocs").removeHandler(warning_counter)
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ from mknodes.utils import log, resources
4
+
5
+
6
+ logger = log.get_logger(__name__)
7
+
8
+
9
+ class BuildBackend:
10
+ def collect(self, files: dict[str, str | bytes], reqs: resources.Resources):
11
+ self.collect_extensions(reqs.markdown_extensions)
12
+ self.collect_js_links(reqs.js_links)
13
+ self.collect_js_files(reqs.js_files)
14
+ self.collect_css(reqs.css)
15
+ self.collect_templates(reqs.templates)
16
+ self.collect_files(files)
17
+ self.collect_assets(reqs.assets)
18
+
19
+ def collect_files(self, files):
20
+ pass
21
+
22
+ def collect_js_links(self, js_links):
23
+ pass
24
+
25
+ def collect_js_files(self, js_files):
26
+ pass
27
+
28
+ def collect_css(self, css):
29
+ pass
30
+
31
+ # def collect_css_links(self, css):
32
+ # pass
33
+
34
+ def collect_extensions(self, extensions):
35
+ pass
36
+
37
+ def collect_templates(self, templates):
38
+ pass
39
+
40
+ def collect_assets(self, assets):
41
+ pass
42
+
43
+
44
+ if __name__ == "__main__":
45
+ b = BuildBackend()
@@ -0,0 +1,49 @@
1
+ """Link replacer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ import re
7
+ import urllib.parse
8
+
9
+ from mkdocs.plugins import get_plugin_logger
10
+ from mknodes.utils import helpers
11
+
12
+
13
+ logger = get_plugin_logger(__name__)
14
+
15
+
16
+ # For Regex, match groups are:
17
+ # 0: Whole markdown link e.g. [Alt-text](url)
18
+ # 1: Alt text
19
+ # 2: Full URL e.g. url + hash anchor
20
+ # 3: Filename e.g. filename.md
21
+ # 4: File extension e.g. .md, .png, etc.
22
+ # 5. hash anchor e.g. #my-sub-heading-link
23
+ AUTOLINK_RE = r"\[([^\]]+)\]\((([^)/]+\.(md|png|jpg))(#.*)*)\)"
24
+
25
+
26
+ class LinkReplacer:
27
+ def __init__(self):
28
+ self.mapping = collections.defaultdict(list)
29
+ self.page_url = ""
30
+
31
+ def __call__(self, match):
32
+ filename = urllib.parse.unquote(match.group(3).strip())
33
+ if filename not in self.mapping:
34
+ return f"`{match.group(1)}`"
35
+ filenames = self.mapping[filename]
36
+ if len(filenames) > 1:
37
+ text = "%s: %s has %s targets"
38
+ logger.debug(text, self.page_url, len(filenames), match.group(3))
39
+ new_link = helpers.relative_url(self.page_url, filenames[0])
40
+ return match.group(0).replace(match.group(2), new_link)
41
+ # new_text = new_text.replace("\\", "/")
42
+ # text = "LinkReplacer: : %s -> %s"
43
+ # logger.debug(text, match.group(3), new_text)
44
+
45
+ def replace(self, markdown: str, uri: str) -> str:
46
+ if uri.endswith("SUMMARY.md"):
47
+ return markdown
48
+ self.page_url = uri
49
+ return re.sub(AUTOLINK_RE, self, markdown)
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import pathlib
5
+
6
+ from mknodes.utils import log, pathhelpers
7
+
8
+ from mkdocs_mknodes.plugin import buildbackend
9
+
10
+
11
+ logger = log.get_logger(__name__)
12
+
13
+
14
+ class MarkdownBackend(buildbackend.BuildBackend):
15
+ def __init__(
16
+ self,
17
+ directory: str | os.PathLike | None = None,
18
+ extension: str = ".md",
19
+ ):
20
+ self.extension = extension
21
+ self.directory = pathlib.Path(directory or ".")
22
+ self._files: dict[str, str | bytes] = {}
23
+
24
+ def collect_files(self, files: dict[str, str | bytes]):
25
+ for k, v in files.items():
26
+ logger.debug("%s: Writing file to %r", type(self).__name__, str(k))
27
+ target_path = (self.directory / k).with_suffix(self.extension).as_posix()
28
+ self._files[str(target_path)] = v
29
+ pathhelpers.write_file(v, str(target_path))
30
+
31
+ # def write(self):
32
+ # for k, v in self._files.items():
33
+ # pathhelpers.write_file(v, k)
34
+
35
+
36
+ if __name__ == "__main__":
37
+ cfg = MarkdownBackend()