feat: add DataFile content class

This commit is contained in:
Corentin 2024-05-20 08:21:45 +02:00
parent b968cde1c2
commit e0598cc7b7
6 changed files with 37 additions and 2 deletions

View File

@ -1,5 +1,8 @@
from functools import cache from functools import cache
from pathlib import Path from pathlib import Path
from typing import Any, Iterator
from yaml import Loader, load
class Content: class Content:
@ -31,5 +34,20 @@ class ContentDirectory(Content):
if child_path.is_dir(): if child_path.is_dir():
return ContentDirectory(child_path) return ContentDirectory(child_path)
if child_path.is_file() and child_path.suffix in [".yml", ".yaml", ".json"]:
return DataFile(child_path)
raise NotImplementedError() raise NotImplementedError()
class DataFile(Content):
def __init__(self, path: Path) -> None:
super().__init__(path)
with path.open("r", encoding="utf-8") as data_file:
self.__data = load(data_file, Loader)
def __getitem__(self, key: Any) -> Any:
return self.__data.get(key)
def __iter__(self) -> Iterator[Any]:
yield from self.__data

View File

@ -12,8 +12,7 @@ def lint(session: Session) -> None:
@session() @session()
def mypy(session: Session) -> None: def mypy(session: Session) -> None:
session.install("-e", ".[dev]") session.install("-e", ".[dev]", "mypy", "types-PyYAML")
session.install("mypy")
session.run("mypy") session.run("mypy")

View File

@ -14,6 +14,7 @@ dependencies = [
"click", "click",
"jinja2", "jinja2",
"pymarkdown", "pymarkdown",
"pyyaml",
] ]
[project.optional-dependencies] [project.optional-dependencies]

View File

@ -16,3 +16,17 @@ def test_load_errors(datadir: Path) -> None:
with raises(FileNotFoundError): with raises(FileNotFoundError):
directory.load(Path("otters/i-dont-exist")) directory.load(Path("otters/i-dont-exist"))
with raises(NotADirectoryError):
directory.load(Path("otters/steven.yml/child"))
def test_load_data(datadir: Path) -> None:
content = ContentDirectory(datadir)
steven = content.load(Path("otters/steven.yml"))
assert steven["name"] == "Steven"
assert steven["mood"] == "Angry"
otter_list = content.load(Path("otters/otter_list.json"))
assert list(otter_list) == ["steven", "peter"]

View File

@ -0,0 +1 @@
["steven", "peter"]

View File

@ -0,0 +1,2 @@
name: Steven
mood: Angry