Coverage for mapology/template_loader.py: 15.91%
26 statements
« prev ^ index » next coverage.py v7.4.1, created at 2024-02-04 20:27:38 +00:00
« prev ^ index » next coverage.py v7.4.1, created at 2024-02-04 20:27:38 +00:00
1"""Loader function for templates."""
3import importlib.resources
4import pathlib
5from typing import List, Union
7ENCODING = 'utf-8'
8RESOURCES = (
9 'airport_page_template.html',
10 'country_index_template.html',
11 'country_page_template.html',
12 'ndb_index_template.html',
13 'prefix_index_template.html',
14 'prefix_page_template.html',
15 'search_index_template.html',
16)
19def load_html(resource: str, is_complete_path: bool = False) -> str:
20 """Load the template either from the package resources or an external path."""
21 if is_complete_path:
22 with open(resource, 'rt', encoding=ENCODING) as handle:
23 return handle.read()
24 else:
25 with importlib.resources.path(__package__, resource) as html_template_path:
26 with open(html_template_path, 'rt', encoding=ENCODING) as handle:
27 return handle.read()
30def eject(argv: Union[List[str], None] = None) -> int:
31 """Eject the templates into the folder given (default EJECTED) and create the folder if it does not exist."""
32 argv = argv if argv else ['']
33 into = argv[0]
34 if not into.strip():
35 into = 'EJECTED'
36 into_path = pathlib.Path(into)
37 into_path.mkdir(parents=True, exist_ok=True)
38 for resource in RESOURCES:
39 write_to = into_path / resource
40 with importlib.resources.path(__package__, resource) as html_template_path:
41 with open(html_template_path, 'rt', encoding=ENCODING) as handle:
42 with open(write_to, 'wt', encoding=ENCODING) as target:
43 target.write(handle.read())
45 return 0