file_integrity.py: make sure file_fd is always closed on exit

This commit is contained in:
Rayyan Ansari 2022-11-15 17:20:50 +00:00
parent f3f6e3f448
commit c209daec63
1 changed files with 9 additions and 3 deletions

View File

@ -128,6 +128,7 @@ class IntegrityCheckedFile(FileLikeWrapper):
self.writing = write self.writing = write
mode = "wb" if write else "rb" mode = "wb" if write else "rb"
self.file_fd = override_fd or open(path, mode) self.file_fd = override_fd or open(path, mode)
self.file_opened = override_fd is None
self.digests = {} self.digests = {}
hash_cls = XXH64FileHashingWrapper hash_cls = XXH64FileHashingWrapper
@ -190,9 +191,14 @@ class IntegrityCheckedFile(FileLikeWrapper):
def __exit__(self, exc_type, exc_val, exc_tb): def __exit__(self, exc_type, exc_val, exc_tb):
exception = exc_type is not None exception = exc_type is not None
if not exception:
self.hash_part("final", is_final=True) try:
self.hasher.__exit__(exc_type, exc_val, exc_tb) if not exception:
self.hash_part("final", is_final=True)
self.hasher.__exit__(exc_type, exc_val, exc_tb)
finally:
if self.file_opened:
self.file_fd.close()
if exception: if exception:
return return
if self.writing: if self.writing: