diff --git a/src/fsutil/info.py b/src/fsutil/info.py index c7822a6..4255584 100644 --- a/src/fsutil/info.py +++ b/src/fsutil/info.py @@ -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 diff --git a/tests/test_info.py b/tests/test_info.py index 91ee077..2de5c86 100644 --- a/tests/test_info.py +++ b/tests/test_info.py @@ -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)