Coverage for src/epublib/resources/create.py: 100%
32 statements
« prev ^ index » next coverage.py v7.10.7, created at 2025-10-06 15:17 -0300
« prev ^ index » next coverage.py v7.10.7, created at 2025-10-06 15:17 -0300
1from pathlib import Path
2from typing import IO
3from zipfile import ZipInfo
5from epublib.exceptions import EPUBError
6from epublib.media_type 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)
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)
25 if media_type is None:
26 media_type = MediaType.from_filename(zipinfo.filename)
27 else:
28 media_type = MediaType(media_type)
30 if (
31 media_type is None
32 or Path(zipinfo.filename).parts[0] == "META-INF"
33 or zipinfo.filename == "mimetype"
34 ):
35 return Resource(file, zipinfo)
37 if media_type is MediaType.NCX:
38 return NCXFile(file, zipinfo, media_type)
40 if media_type is MediaType.IMAGE_SVG or media_type is MediaType.XHTML:
41 if is_nav:
42 return NavigationDocument(file, zipinfo, media_type)
43 return ContentDocument(file, zipinfo, media_type)
45 if is_nav:
46 raise EPUBError(
47 f"Found media type of '{zipinfo.filename}' to be "
48 f"'{media_type}', which is incompatible with argument "
49 "'is_nav=True'. Only XHTML or SVG documents can be the "
50 "navigation document"
51 )
53 return PublicationResource(file, zipinfo, media_type)
56def create_resource_from_path(
57 path: str | Path,
58 info: ZipInfo | str | Path | None = None,
59 media_type: MediaType | str | None = None,
60 is_nav: bool = False,
61):
62 file = open(path, "rb")
64 if info is None:
65 info = Path(path).name
67 zipinfo = info
69 if not isinstance(info, ZipInfo):
70 zipinfo = ZipInfo.from_file(path, info, strict_timestamps=False)
72 return create_resource(file, zipinfo, media_type, is_nav)