|
1 | 1 | from __future__ import annotations
|
2 | 2 |
|
| 3 | +import functools |
3 | 4 | import pathlib
|
4 | 5 | from typing import TYPE_CHECKING, Any
|
5 | 6 |
|
6 | 7 | import jinja2
|
| 8 | +import upathtools |
7 | 9 |
|
8 | 10 | from jinjarope import envglobals, loaders as loaders_, utils
|
9 | 11 |
|
|
14 | 16 | import fsspec
|
15 | 17 |
|
16 | 18 |
|
| 19 | +@functools.cache |
| 20 | +async def get_template(path: str) -> str: |
| 21 | + return await upathtools.read_path(path) |
| 22 | + |
| 23 | + |
17 | 24 | class FsSpecProtocolPathLoader(loaders_.LoaderMixin, jinja2.BaseLoader):
|
18 | 25 | """A jinja loader for fsspec filesystems.
|
19 | 26 |
|
@@ -48,6 +55,18 @@ def get_source(
|
48 | 55 | path = pathlib.Path(template).as_posix()
|
49 | 56 | return src, path, lambda: True
|
50 | 57 |
|
| 58 | + async def get_source_async( |
| 59 | + self, |
| 60 | + environment: jinja2.Environment | None, |
| 61 | + template: str, |
| 62 | + ) -> tuple[str, str, Callable[[], bool] | None]: |
| 63 | + try: |
| 64 | + src = await get_template(template) |
| 65 | + except FileNotFoundError as e: |
| 66 | + raise jinja2.TemplateNotFound(template) from e |
| 67 | + path = pathlib.Path(template).as_posix() |
| 68 | + return src, path, lambda: True |
| 69 | + |
51 | 70 | def list_templates(self) -> list[str]:
|
52 | 71 | return []
|
53 | 72 |
|
@@ -153,6 +172,23 @@ def get_source(
|
153 | 172 | path = pathlib.Path(template).as_posix()
|
154 | 173 | return src, path, lambda: True
|
155 | 174 |
|
| 175 | + async def get_source_async( |
| 176 | + self, |
| 177 | + environment: jinja2.Environment, |
| 178 | + template: str, |
| 179 | + ) -> tuple[str, str, Callable[[], bool] | None]: |
| 180 | + from upathtools.async_ops import get_async_fs |
| 181 | + |
| 182 | + fs = await get_async_fs(self.fs) |
| 183 | + try: |
| 184 | + file = await fs.open_async(template) |
| 185 | + async with file: |
| 186 | + src = await file.read().decode() # pyright: ignore |
| 187 | + except FileNotFoundError as e: |
| 188 | + raise jinja2.TemplateNotFound(template) from e |
| 189 | + path = pathlib.Path(template).as_posix() |
| 190 | + return src, path, lambda: True |
| 191 | + |
156 | 192 |
|
157 | 193 | if __name__ == "__main__":
|
158 | 194 | from jinjarope import Environment
|
|
0 commit comments