Skip to content

Commit

Permalink
Add tests for Files
Browse files Browse the repository at this point in the history
  • Loading branch information
daizutabi committed Feb 11, 2024
1 parent 3e61f97 commit 4e6d0b3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/mkapi/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ def on_config(self, config: MkDocsConfig, **kwargs) -> MkDocsConfig:
cache_clear()
self.bar = None
self.uri_width = 0

self.page_title = _get_function("page_title", self)
self.section_title = _get_function("section_title", self)
self.toc_title = _get_function("toc_title", self)
Expand Down Expand Up @@ -111,6 +112,7 @@ def on_page_markdown(self, markdown: str, page: MkDocsPage, **kwargs) -> str:
"""Convert Markdown source to intermediate version."""
uri = page.file.src_uri
page_ = self.pages[uri]

if page_.kind == "source":
anchor = self.config.docs_anchor
else:
Expand All @@ -121,6 +123,7 @@ def on_page_markdown(self, markdown: str, page: MkDocsPage, **kwargs) -> str:
except Exception as e: # noqa: BLE001
if self.config.debug:
raise

msg = f"{uri}:{type(e).__name__}: {e}"
logger.warning(msg)
return markdown
Expand All @@ -138,8 +141,10 @@ def on_page_content(

if page_.kind in ["object", "source"]:
_replace_toc(page.toc, self.toc_title)

if page_.kind == "source":
html = convert_source(html, page_.path, self.config.docs_anchor)

self._update_bar(page.file.src_uri)
return html

Expand Down Expand Up @@ -179,16 +184,19 @@ def on_shutdown(self) -> None:
def _get_function(name: str, plugin: MkAPIPlugin) -> Callable | None:
if not (path_str := plugin.config.config):
return None

if not path_str.endswith(".py"):
module = importlib.import_module(path_str)
else:
path = Path(path_str)
if not path.is_absolute():
path = Path(plugin.config.config_file_path).parent / path

directory = os.path.normpath(path.parent)
sys.path.insert(0, directory)
module = importlib.import_module(path.stem)
del sys.path[0]

return getattr(module, name, None)


Expand All @@ -205,6 +213,7 @@ def _update_extensions(config: MkDocsConfig, plugin: MkAPIPlugin) -> None: # no
def _watch_directory(name: str, config: MkDocsConfig) -> None:
if not name:
return

name, depth = split_name_depth(name)
if path := get_module_path(name):
path = str(path.parent if depth else path)
Expand All @@ -215,15 +224,18 @@ def _watch_directory(name: str, config: MkDocsConfig) -> None:
def _mkdir(path: Path, paths: list[Path]) -> None:
if path.exists() and path not in paths:
logger.warning(f"API directory exists: {path}")

ans = input("Delete the directory? [yes/no] ")
if ans.lower() == "yes":
logger.info(f"Deleting API directory: {path}")
shutil.rmtree(path)
else:
logger.error("Delete the directory manually.")
sys.exit()

if not path.exists():
msg = f"Making API directory: {path}"

logger.info(msg)
path.mkdir(parents=True)
paths.append(path)
Expand Down Expand Up @@ -283,35 +295,43 @@ def predicate(name: str) -> bool:

with warnings.catch_warnings():
warnings.simplefilter("ignore")

spinner = Halo()
spinner.start()

mkapi.nav.update(
config.nav,
_create_page,
plugin.section_title,
plugin.page_title,
predicate,
)

spinner.stop()


def _collect_stylesheets(config: MkDocsConfig, plugin: MkAPIPlugin) -> list[File]: # noqa: ARG001
root = Path(mkapi.__file__).parent / "stylesheets"

docs_dir = config.docs_dir
config.docs_dir = root.as_posix()
stylesheet_files = get_files(config)
config.docs_dir = docs_dir

theme_name = config.theme.name or "mkdocs"

files: list[File] = []
css: list[str] = []
for file in stylesheet_files:
path = Path(file.src_path).as_posix()

if path.endswith("mkapi-common.css"):
files.insert(0, file)
css.insert(0, path)
elif path.endswith(f"mkapi-{theme_name}.css"):
files.append(file)
css.append(path)

config.extra_css = [*css, *config.extra_css]
return files

Expand All @@ -323,8 +343,10 @@ def _replace_toc(
) -> None:
for link in toc:
link.title = re.sub(r"\s+\[.+?\]", "", link.title) # Remove source link.

if title:
link.title = title(link.title, depth)
else:
link.title = link.title.split(".")[-1] # Remove prefix.

_replace_toc(link.children, title, depth + 1)
8 changes: 7 additions & 1 deletion tests/test_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
from mkdocs.config import load_config
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.plugins import PluginCollection
from mkdocs.structure.files import Files
from mkdocs.theme import Theme

import mkapi
from mkapi.plugins import MkAPIConfig, MkAPIPlugin, _get_function
from mkapi.plugins import MkAPIConfig, MkAPIPlugin, _collect_stylesheets, _get_function


@pytest.fixture(scope="module")
Expand Down Expand Up @@ -119,5 +120,10 @@ def test_on_config(config: MkDocsConfig, mkapi_plugin: MkAPIPlugin):
assert (Path(config.docs_dir) / path).exists()


def test_collect_stylesheets(config: MkDocsConfig, mkapi_plugin: MkAPIPlugin):
files = Files(_collect_stylesheets(config, mkapi_plugin))
assert files.media_files()


def test_build(config: MkDocsConfig):
assert build(config) is None

0 comments on commit 4e6d0b3

Please sign in to comment.