Skip to content

Commit

Permalink
POC: demonstrate mkdocs generated_by detection wrt mkdocs#3344
Browse files Browse the repository at this point in the history
  • Loading branch information
ultrabug committed Aug 23, 2023
1 parent 9cc8f24 commit b2cefe4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
14 changes: 14 additions & 0 deletions docs/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from pathlib import Path

from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import File
from mkdocs.structure.nav import Page


Expand Down Expand Up @@ -31,3 +32,16 @@ def replacement(m: re.Match) -> str:
markdown,
flags=re.MULTILINE,
)


def on_files(files, config):
new_file = open("/tmp/this_file_was_generated.md", "wb").write(b"# Test file")
files.append(
File(
"this_file_was_generated.md",
"/tmp",
config.site_dir,
config.use_directory_urls
)
)
return files
11 changes: 11 additions & 0 deletions mkdocs/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""
from __future__ import annotations

import inspect
import logging
import sys
from typing import TYPE_CHECKING, Any, Callable, Generic, MutableMapping, TypeVar, overload
Expand Down Expand Up @@ -504,12 +505,22 @@ def run_event(self, name: str, item=None, **kwargs):
log.debug(f'Running {len(events)} `{name}` events')
for method in events:
if pass_item:
if name == "files":
before_on_files_src_uris = set(item.src_uris)
result = method(item, **kwargs)
else:
result = method(**kwargs)
# keep item if method returned `None`
if result is not None:
item = result
if name == "files":
after_on_files_src_uris = set(result.src_uris)
files_added_by_plugin = after_on_files_src_uris.difference(before_on_files_src_uris)
log.warning(f"{files_added_by_plugin=}")
for src_uri in files_added_by_plugin:
item._src_uris[src_uri].generated_by = inspect.getmodule(method).__name__
log.warning(item._src_uris[src_uri])

return item

def on_startup(self, *, command: Literal['build', 'gh-deploy', 'serve'], dirty: bool) -> None:
Expand Down
6 changes: 5 additions & 1 deletion mkdocs/structure/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,9 @@ def dest_path(self, value):

page: Page | None

generated_by: str | None = None
"""The name of the plugin which have generated the file or None if the file is part of docs_dir."""

def __init__(
self,
path: str,
Expand Down Expand Up @@ -243,9 +246,10 @@ def __eq__(self, other) -> bool:
)

def __repr__(self):
generated_by = f", generated_by='{self.generated_by}'" if self.generated_by else ""
return (
f"File(src_uri='{self.src_uri}', dest_uri='{self.dest_uri}',"
f" name='{self.name}', url='{self.url}')"
f" name='{self.name}', url='{self.url}'{generated_by})"
)

def _get_stem(self) -> str:
Expand Down

0 comments on commit b2cefe4

Please sign in to comment.