From 0a1c4a16992da8d6e2b5b10df0d560f52abe8154 Mon Sep 17 00:00:00 2001 From: Daniel Bauer Date: Fri, 24 Jan 2025 11:09:25 +0100 Subject: [PATCH] fix: make sure zip stream buffer is always properly closed --- rocrate/rocrate.py | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py index 32ecc764..be42cb31 100644 --- a/rocrate/rocrate.py +++ b/rocrate/rocrate.py @@ -482,23 +482,22 @@ def write_zip(self, out_path): def stream_zip(self): """ Create a stream of bytes representing the RO-Crate as a ZIP file. """ - buffer = MemoryBuffer() - with zipfile.ZipFile(buffer, mode='w', compression=zipfile.ZIP_DEFLATED) as archive: - for writeable_entity in self.data_entities + self.default_entities: - current_file_path, current_out_file = None, None - for path, chunk in writeable_entity.stream(): - if path != current_file_path: - if current_out_file: - current_out_file.close() - current_file_path = path - current_out_file = archive.open(path, mode='w') - current_out_file.write(chunk) - yield buffer.read() - if current_out_file: - current_out_file.close() - - yield buffer.read() - buffer.close() + with MemoryBuffer() as buffer: + with zipfile.ZipFile(buffer, mode='w', compression=zipfile.ZIP_DEFLATED) as archive: + for writeable_entity in self.data_entities + self.default_entities: + current_file_path, current_out_file = None, None + for path, chunk in writeable_entity.stream(): + if path != current_file_path: + if current_out_file: + current_out_file.close() + current_file_path = path + current_out_file = archive.open(path, mode='w') + current_out_file.write(chunk) + yield buffer.read() + if current_out_file: + current_out_file.close() + + yield buffer.read() def add_workflow( self, source=None, dest_path=None, fetch_remote=False, validate_url=False, properties=None,