Coverage for src/epublib/resources/create.py: 100%

31 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-18 16:07 -0300

1from pathlib import Path 

2from typing import IO 

3from zipfile import ZipInfo 

4 

5from epublib.exceptions import EPUBError 

6from epublib.mediatype import MediaType 

7from epublib.nav.resource import NavigationDocument 

8from epublib.ncx.resource import NCXFile 

9from epublib.resources import ( 

10 ContentDocument, 

11 PublicationResource, 

12 Resource, 

13 info_to_zipinfo, 

14) 

15 

16 

17def create_resource( 

18 file: IO[bytes] | bytes, 

19 info: ZipInfo | str | Path, 

20 media_type: MediaType | str | None = None, 

21 is_nav: bool = False, 

22): 

23 zipinfo = info_to_zipinfo(info) 

24 

25 if media_type is None: 

26 media_type = MediaType.from_filename(zipinfo.filename) 

27 

28 if ( 

29 media_type is None 

30 or Path(zipinfo.filename).parts[0] == "META-INF" 

31 or zipinfo.filename == "mimetype" 

32 ): 

33 return Resource(file, zipinfo) 

34 

35 if media_type is MediaType.NCX: 

36 return NCXFile(file, zipinfo, media_type) 

37 

38 if media_type is MediaType.IMAGE_SVG or media_type is MediaType.XHTML: 

39 if is_nav: 

40 return NavigationDocument(file, zipinfo, media_type) 

41 return ContentDocument(file, zipinfo, media_type) 

42 

43 if is_nav: 

44 raise EPUBError( 

45 f"Found media type of '{zipinfo.filename}' to be " 

46 f"'{media_type}', which is incompatible with argument " 

47 "'is_nav=True'. Only XHTML or SVG documents can be the " 

48 "navigation document" 

49 ) 

50 

51 return PublicationResource(file, zipinfo, media_type) 

52 

53 

54def create_resource_from_path( 

55 path: str | Path, 

56 info: ZipInfo | str | Path | None = None, 

57 media_type: MediaType | str | None = None, 

58 is_nav: bool = False, 

59): 

60 file = open(path, "rb") 

61 

62 if info is None: 

63 info = Path(path).name 

64 

65 zipinfo = info 

66 

67 if not isinstance(info, ZipInfo): 

68 zipinfo = ZipInfo.from_file(path, info, strict_timestamps=False) 

69 

70 return create_resource(file, zipinfo, media_type, is_nav)