Skip to content

Commit

Permalink
fix reading from a BytesIO
Browse files Browse the repository at this point in the history
  • Loading branch information
jdum committed Dec 25, 2023
1 parent 469bcd0 commit f10de01
Showing 1 changed file with 15 additions and 13 deletions.
28 changes: 15 additions & 13 deletions odfdo/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@
from .utils import to_bytes, to_str


def normalize_path(path: str) -> str:
if path.endswith("/"): # folder
return PurePath(path[:-1]).as_posix() + "/"
return PurePath(path).as_posix()


class Container:
"""Representation of the ODF file."""

Expand Down Expand Up @@ -110,16 +116,20 @@ def from_template(cls, template: str | Path) -> Container:
return clone

def _read_zip(self) -> None:
if isinstance(self.__path_like, io.BytesIO):
self.__path_like.seek(0)
with ZipFile(self.__path_like) as zf:
mimetype = zf.read("mimetype").decode("utf8", "ignore")
if mimetype not in ODF_MIMETYPES:
raise ValueError(f"Document of unknown type {mimetype}")
self.__parts["mimetype"] = to_bytes(mimetype)
if self.path is None:
if isinstance(self.__path_like, io.BytesIO):
self.__path_like.seek(0)
# read the full file at once and forget file
with ZipFile(self.__path_like) as zf:
for name in zf.namelist():
upath = PurePath(name).as_posix()
upath = normalize_path(name)
self.__parts[upath] = zf.read(name)
self.__path_like = None

Expand Down Expand Up @@ -179,10 +189,7 @@ def _get_zip_part(self, name: str) -> bytes | None:
"""Get bytes of a part from the Zip ODF file. No cache."""
try:
with ZipFile(self.path) as zf:
if name.endswith("/"): # folder
upath = PurePath(name[:-1]).as_posix() + "/"
else:
upath = PurePath(name).as_posix()
upath = normalize_path(name)
self.__parts[upath] = zf.read(name)
return self.__parts[upath]
except BadZipfile:
Expand All @@ -193,10 +200,7 @@ def _get_all_zip_part(self) -> None:
try:
with ZipFile(self.path) as zf:
for name in zf.namelist():
if name.endswith("/"): # folder
upath = PurePath(name[:-1]).as_posix() + "/"
else:
upath = PurePath(name).as_posix()
upath = normalize_path(name)
self.__parts[upath] = zf.read(name)
except BadZipfile:
pass
Expand Down Expand Up @@ -271,10 +275,8 @@ def get_parts(self) -> list[str]:
parts = []
with ZipFile(self.path) as zf:
for name in zf.namelist():
if name.endswith("/"):
parts.append(PurePath(name[:-1]).as_posix() + "/")
else:
parts.append(PurePath(name).as_posix())
upath = normalize_path(name)
parts.append(upath)
return parts
elif self.__packaging == "folder":
return self._get_folder_parts()
Expand Down

0 comments on commit f10de01

Please sign in to comment.