feat: add DataFile content class
This commit is contained in:
parent
b968cde1c2
commit
e0598cc7b7
|
|
@ -1,5 +1,8 @@
|
|||
from functools import cache
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterator
|
||||
|
||||
from yaml import Loader, load
|
||||
|
||||
|
||||
class Content:
|
||||
|
|
@ -31,5 +34,20 @@ 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)
|
||||
|
||||
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
|
||||
|
|
|
|||
|
|
@ -12,8 +12,7 @@ def lint(session: Session) -> None:
|
|||
|
||||
@session()
|
||||
def mypy(session: Session) -> None:
|
||||
session.install("-e", ".[dev]")
|
||||
session.install("mypy")
|
||||
session.install("-e", ".[dev]", "mypy", "types-PyYAML")
|
||||
session.run("mypy")
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ dependencies = [
|
|||
"click",
|
||||
"jinja2",
|
||||
"pymarkdown",
|
||||
"pyyaml",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
|
|
|||
|
|
@ -16,3 +16,17 @@ def test_load_errors(datadir: Path) -> None:
|
|||
|
||||
with raises(FileNotFoundError):
|
||||
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"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
["steven", "peter"]
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
name: Steven
|
||||
mood: Angry
|
||||
Loading…
Reference in New Issue