refactor: load and write content as bytes

Allow loading and transforming other things than text files (images)
This commit is contained in:
Corentin 2024-05-22 00:19:37 +02:00
parent f7bd1fd62f
commit 7a86eb432c
2 changed files with 7 additions and 5 deletions

View File

@ -23,6 +23,8 @@ class Content(Generic[TData]):
return self.__data return self.__data
def __str__(self) -> str: def __str__(self) -> str:
if isinstance(self.__data, bytes):
return self.__data.decode("utf-8")
return str(self.__data) return str(self.__data)

View File

@ -70,7 +70,7 @@ class Context:
self.__render(source, self.__output_directory / output, **context) self.__render(source, self.__output_directory / output, **context)
@pass_context @pass_context
def __load(self, context: JinjaContext, path: str | Path | ContentField) -> Content[str]: def __load(self, context: JinjaContext, path: str | Path | ContentField) -> Content[bytes]:
if isinstance(path, ContentField): if isinstance(path, ContentField):
path = path.as_path() path = path.as_path()
@ -82,13 +82,13 @@ class Context:
else: else:
localized_path = self.__content_directory / path localized_path = self.__content_directory / path
with localized_path.open("r", encoding="utf-8") as content_file: with localized_path.open("rb") as content_file:
return Content(localized_path, content_file.read(), current_language) return Content(localized_path, content_file.read(), current_language)
@pass_context @pass_context
def __glob( def __glob(
self, context: JinjaContext, pattern: str, include_base_language: bool = False self, context: JinjaContext, pattern: str, include_base_language: bool = False
) -> Iterator[Content[str]]: ) -> Iterator[Content[bytes]]:
roots: list[Path] = [] roots: list[Path] = []
current_language = self.current_language current_language = self.current_language
if current_language is None: if current_language is None:
@ -105,11 +105,11 @@ class Context:
for path in paths: for path in paths:
yield self.__load(context, path) yield self.__load(context, path)
def __write(self, content: Content[str]) -> Path: def __write(self, content: Content[bytes]) -> Path:
relative_path = content.path.relative_to(self.__content_directory) relative_path = content.path.relative_to(self.__content_directory)
output_path = self.__output_directory / relative_path output_path = self.__output_directory / relative_path
output_path.parent.mkdir(parents=True, exist_ok=True) output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("w") as output_file: with output_path.open("wb") as output_file:
output_file.write(content.data) output_file.write(content.data)
return Path(f"/{relative_path}") return Path(f"/{relative_path}")