Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions src/fsutil/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,12 @@ def get_file_hash(path: PathIn | IO[bytes], *, func: str = "md5") -> str:
if fileobj.seekable():
position = fileobj.tell()
fileobj.seek(0)
for chunk in iter(lambda: fileobj.read(4096), b""):
hash.update(chunk)
if position is not None:
fileobj.seek(position)
try:
for chunk in iter(lambda: fileobj.read(4096), b""):
hash.update(chunk)
finally:
if position is not None:
fileobj.seek(position)
hash_hex = hash.hexdigest()
return hash_hex

Expand Down
12 changes: 12 additions & 0 deletions tests/test_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,18 @@ def test_get_file_hash_with_file_like_object():
assert file_hash == "b10a8db164e0754105b7a99be72e3fe5"


def test_get_file_hash_restores_position_after_read_error():
class FailingStream(io.BytesIO):
def read(self, size=-1):
raise OSError("read failed")

with FailingStream(b"contents") as file:
file.seek(3)
with pytest.raises(OSError, match="read failed"):
fsutil.get_file_hash(file)
assert file.tell() == 3


def test_get_file_hash_with_file_like_object_restores_position():
file = io.BytesIO(b"Hello World")
file.seek(6)
Expand Down
Loading