feat: add Markdown file content class

This commit is contained in:
Corentin 2024-05-20 08:53:29 +02:00
parent e0598cc7b7
commit bf443a39e1
5 changed files with 39 additions and 5 deletions

View File

@ -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

View File

@ -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")

View File

@ -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]

View File

@ -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 == "<p>Content</p>"
assert page.meta["title"] == "Title"

View File

@ -0,0 +1,5 @@
---
title: Title
---
Content