Browse Source

fixup: invert nesting of context managers

cleaner teardown of contexts:

close mmap, close src_fd (reading), close dst_fd (and rename)

maybe it was not a real problem to rename a still open-for-reading / mmapped file,
but in any case it is cleaner like now.
Thomas Waldmann 4 years ago
parent
commit
1d9c67de8d
1 changed files with 11 additions and 11 deletions
  1. 11 11
      src/borg/repository.py

+ 11 - 11
src/borg/repository.py

@@ -1444,14 +1444,14 @@ class LoggedIO:
             with SaveFile(filename, binary=True) as fd:
                 fd.write(MAGIC)
             return
-        with open(filename, 'rb') as src_fd:
-            # note: file must not be 0 size or mmap() will crash.
-            with mmap.mmap(src_fd.fileno(), 0, access=mmap.ACCESS_READ) as mm:
-                # memoryview context manager is problematic, see https://bugs.python.org/issue35686
-                data = memoryview(mm)
-                d = data
-                try:
-                    with SaveFile(filename, binary=True) as dst_fd:
+        with SaveFile(filename, binary=True) as dst_fd:
+            with open(filename, 'rb') as src_fd:
+                # note: file must not be 0 size or mmap() will crash.
+                with mmap.mmap(src_fd.fileno(), 0, access=mmap.ACCESS_READ) as mm:
+                    # memoryview context manager is problematic, see https://bugs.python.org/issue35686
+                    data = memoryview(mm)
+                    d = data
+                    try:
                         dst_fd.write(MAGIC)
                         while len(d) >= self.header_fmt.size:
                             crc, size, tag = self.header_fmt.unpack(d[:self.header_fmt.size])
@@ -1463,9 +1463,9 @@ class LoggedIO:
                                 continue
                             dst_fd.write(d[:size])
                             d = d[size:]
-                finally:
-                    del d
-                    data.release()
+                    finally:
+                        del d
+                        data.release()
 
     def read(self, segment, offset, id, read_data=True):
         """