Coverage for bookbuilderpy/resources/_resource.py: 80%

25 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-17 23:15 +0000

1"""The package for loading text templates and resources.""" 

2import os.path 

3from importlib import resources # nosem 

4 

5from bookbuilderpy.path import Path, copy_pure 

6from bookbuilderpy.strings import ( 

7 enforce_non_empty_str, 

8 enforce_non_empty_str_without_ws, 

9) 

10 

11 

12def load_resource(name: str, source_dir: str, dest_dir: str) -> \ 

13 Path | None: 

14 """ 

15 Load a text resource or template for the use with pandoc. 

16 

17 :param name: the template name 

18 :param source_dir: the source directory 

19 :param dest_dir: the destination directory 

20 :return: the fully qualified path to the resource file if it was created, 

21 or None if no new file was created 

22 """ 

23 input_dir = Path.directory(source_dir) 

24 output_dir = Path.directory(dest_dir) 

25 input_dir.enforce_neither_contains(output_dir) 

26 name = enforce_non_empty_str_without_ws(name) 

27 

28 if name.startswith(("http://", "https://")) or "//" in name: 

29 return None 

30 

31 output_file = output_dir.resolve_inside(name) 

32 if os.path.exists(output_file): 

33 output_file.enforce_file() 

34 return None 

35 

36 Path.directory(os.path.dirname(output_file)).ensure_dir_exists() 

37 input_file = input_dir.resolve_inside(name) 

38 if os.path.isfile(input_file): 

39 return copy_pure(input_file, output_file) 

40 

41 pack = str(__package__) 

42 if resources.is_resource(package=pack, name=name): 

43 with resources.open_text(package=pack, resource=name) as stream: 

44 output_file.write_all(enforce_non_empty_str(stream.read())) 

45 return output_file 

46 

47 return None