Fix ResourceFork.open and __init__ not closing streams in some cases

This commit is contained in:
dgelessus 2018-02-16 22:30:18 +01:00
parent cbc55fcbc2
commit 2dbf0f7047

View File

@ -188,13 +188,18 @@ class ResourceFile(collections.abc.Mapping):
# If the resource fork doesn't exist, fall back to the data fork. # If the resource fork doesn't exist, fall back to the data fork.
f = open(filename, "rb") f = open(filename, "rb")
else: else:
# Resource fork exists, check if it actually contains anything. try:
if f.read(1): # Resource fork exists, check if it actually contains anything.
# Resource fork contains data, seek back to start before using it. if f.read(1):
f.seek(0) # Resource fork contains data, seek back to start before using it.
else: f.seek(0)
# Resource fork contains no data, fall back to the data fork. else:
f = open(filename, "rb") # Resource fork contains no data, fall back to the data fork.
f.close()
f = open(filename, "rb")
except BaseException:
f.close()
raise
elif rsrcfork: elif rsrcfork:
# Force use of the resource fork. # Force use of the resource fork.
f = open(os.path.join(filename, "..namedfork", "rsrc"), "rb") f = open(os.path.join(filename, "..namedfork", "rsrc"), "rb")
@ -222,18 +227,22 @@ class ResourceFile(collections.abc.Mapping):
self._close_stream: bool = close self._close_stream: bool = close
self._stream: typing.io.BinaryIO = stream self._stream: typing.io.BinaryIO = stream
self._allow_seek: bool try:
if allow_seek is None: self._allow_seek: bool
self._allow_seek = self._stream.seekable() if allow_seek is None:
else: self._allow_seek = self._stream.seekable()
self._allow_seek = allow_seek else:
self._allow_seek = allow_seek
if self._allow_seek: if self._allow_seek:
self._pos = None self._pos = None
self._init_seeking() self._init_seeking()
else: else:
self._pos: int = 0 self._pos: int = 0
self._init_streaming() self._init_streaming()
except BaseException:
self.close()
raise
def _tell(self) -> int: def _tell(self) -> int:
"""Get the current position in the stream. This uses the stream's tell method if seeking is enabled, and an internal counter otherwise.""" """Get the current position in the stream. This uses the stream's tell method if seeking is enabled, and an internal counter otherwise."""