]> arthur.barton.de Git - bup.git/commitdiff
compat: add ExitStack
authorRob Browning <rlb@defaultvalue.org>
Thu, 28 Oct 2021 17:11:05 +0000 (12:11 -0500)
committerRob Browning <rlb@defaultvalue.org>
Mon, 22 Nov 2021 16:35:28 +0000 (10:35 -0600)
For now, just add enough py2 support (since it wasn't too hard) to
handle some forthcoming cases.

Signed-off-by: Rob Browning <rlb@defaultvalue.org>
lib/bup/compat.py

index 7527ae7695590fdae40f2e723c1df2a081c31b9c..68006f5178679e1796ecf55a67da8e761043a5d5 100644 (file)
@@ -13,7 +13,7 @@ py3 = py_maj >= 3
 if py3:
 
     # pylint: disable=unused-import
-    from contextlib import nullcontext
+    from contextlib import ExitStack, nullcontext
     from mmap import mmap
     from os import environb as environ
     from os import fsdecode, fsencode
@@ -176,6 +176,31 @@ else:  # Python 2
             tb = getattr(ex, '__traceback__', None)
             print_exception(type(ex), ex, tb)
 
+    class ExitStack:
+        def __init__(self):
+            self.contexts = []
+
+        def __enter__(self):
+            return self
+
+        def __exit__(self, value_type, value, traceback):
+            init_value = value
+            for ctx in reversed(self.contexts):
+                try:
+                    ctx.__exit__(value_type, value, traceback)
+                except BaseException as ex:
+                    add_ex_tb(ex)
+                    if value:
+                        add_ex_ctx(ex, value)
+                    value_type = type(ex)
+                    value = ex
+                    traceback = ex.__traceback__
+            if value is not init_value:
+                raise value
+
+        def enter_context(self, x):
+            self.contexts.append(x)
+
     def items(x):
         return x.iteritems()