diff --git a/jwebsite/content.py b/jwebsite/content.py index 95a6984..eaf9e7f 100644 --- a/jwebsite/content.py +++ b/jwebsite/content.py @@ -2,6 +2,7 @@ from functools import cache from pathlib import Path from typing import Any, Iterator +from markdown import Markdown from yaml import Loader, load @@ -34,8 +35,11 @@ class ContentDirectory(Content): if child_path.is_dir(): return ContentDirectory(child_path) - if child_path.is_file() and child_path.suffix in [".yml", ".yaml", ".json"]: - return DataFile(child_path) + if child_path.is_file(): + if child_path.suffix in [".yml", ".yaml", ".json"]: + return DataFile(child_path) + if child_path.suffix == ".md": + return MarkdownFile(child_path) raise NotImplementedError() @@ -51,3 +55,19 @@ class DataFile(Content): def __iter__(self) -> Iterator[Any]: yield from self.__data + + +class MarkdownFile(Content): + def __init__(self, path: Path) -> None: + super().__init__(path) + with path.open("r", encoding="utf-8") as markdown_file: + self.__markdown = Markdown(extensions=["full_yaml_metadata"]) + self.__html = self.__markdown.convert(markdown_file.read()) + + @property + def html(self) -> str: + return self.__html + + @property + def meta(self) -> Any: + return self.__markdown.Meta # type: ignore diff --git a/noxfile.py b/noxfile.py index 1139d33..9b90cf1 100644 --- a/noxfile.py +++ b/noxfile.py @@ -12,7 +12,7 @@ def lint(session: Session) -> None: @session() def mypy(session: Session) -> None: - session.install("-e", ".[dev]", "mypy", "types-PyYAML") + session.install("-e", ".[dev]", "mypy", "types-PyYAML", "types-Markdown") session.run("mypy") diff --git a/pyproject.toml b/pyproject.toml index 40396ec..c2b1713 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,8 +13,9 @@ readme = "README.md" dependencies = [ "click", "jinja2", - "pymarkdown", + "markdown", "pyyaml", + "markdown-full-yaml-metadata", ] [project.optional-dependencies] @@ -22,7 +23,7 @@ dev = [ "nox", "pytest", "pytest-datadir", - "pytest-coverage" + "pytest-coverage", ] [project.scripts] diff --git a/tests/test_content.py b/tests/test_content.py index 47153a6..07f719a 100644 --- a/tests/test_content.py +++ b/tests/test_content.py @@ -30,3 +30,11 @@ def test_load_data(datadir: Path) -> None: otter_list = content.load(Path("otters/otter_list.json")) assert list(otter_list) == ["steven", "peter"] + + +def test_load_markdown(datadir: Path) -> None: + content = ContentDirectory(datadir) + page = content.load(Path("page.md")) + + assert page.html == "
Content
" + assert page.meta["title"] == "Title" diff --git a/tests/test_content/page.md b/tests/test_content/page.md new file mode 100644 index 0000000..cdc66ee --- /dev/null +++ b/tests/test_content/page.md @@ -0,0 +1,5 @@ +--- +title: Title +--- + +Content