Coverage for liitos/template_loader.py: 100.00%

23 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-22 21:23:25 +00:00

1"""Loader function for templates.""" 

2import pathlib 

3import pkgutil 

4from typing import Union 

5 

6from liitos import ENCODING, PathLike 

7 

8RESOURCES = ( 

9 'templates/approvals.yml', 

10 'templates/bookmatter.tex.in', 

11 'templates/changes.yml', 

12 'templates/driver.tex.in', 

13 'templates/layout.yml', 

14 'templates/meta.yml', 

15 'templates/meta-patch.yml', 

16 'templates/metadata.tex.in', 

17 'templates/mkdocs.yml.in', 

18 'templates/publisher.tex.in', 

19 'templates/setup.tex.in', 

20 'templates/vocabulary.yml', 

21) 

22 

23 

24def load_resource(resource: PathLike, is_complete_path: bool = False) -> str: 

25 """Load the template either from the package resources or an external path.""" 

26 if is_complete_path: 

27 with open(resource, 'rt', encoding=ENCODING) as handle: 

28 return handle.read() 

29 else: 

30 return pkgutil.get_data(__package__, str(resource)).decode(encoding=ENCODING) # type: ignore 

31 

32 

33def eject(argv: Union[list[str], None] = None) -> int: 

34 """Eject the templates into the folder given (default EJECTED) and create the folder if it does not exist.""" 

35 argv = argv if argv else [''] 

36 into = argv[0] 

37 if not into.strip(): 

38 into = 'EJECTED' 

39 into_path = pathlib.Path(into) 

40 (into_path / 'templates').mkdir(parents=True, exist_ok=True) 

41 for resource in RESOURCES: 

42 write_to = into_path / resource 

43 data = pkgutil.get_data(__package__, resource).decode(encoding=ENCODING) # type: ignore 

44 with open(write_to, 'wt', encoding=ENCODING) as target: 

45 target.write(data) 

46 

47 return 0