util/ctx: extract suppress_oserror()

Extract the `suppress_oserror()` function from the ObjectManager and
make it available as utility for other code as well.

This also adds a bunch of tests that verify it works as expected.
This commit is contained in:
David Rheinsberg 2020-05-07 17:07:51 +02:00 committed by Christian Kellner
parent 6e02488a9f
commit 8a195d7502
3 changed files with 80 additions and 15 deletions

View file

@ -7,7 +7,7 @@ import tempfile
import weakref
from typing import Optional
import osbuild.util.rmrf as rmrf
from osbuild.util import ctx, rmrf
from . import treesum
@ -16,19 +16,6 @@ __all__ = [
]
@contextlib.contextmanager
def suppress_oserror(*errnos):
"""A context manager that suppresses any OSError with an errno in `errnos`.
Like contextlib.suppress, but can differentiate between OSErrors.
"""
try:
yield
except OSError as e:
if e.errno not in errnos:
raise e
def mount(source, target, bind=True, ro=True, private=True, mode="0755"):
options = []
if bind:
@ -145,7 +132,7 @@ class Object:
self._check_readers()
self._check_writer()
self.init()
with suppress_oserror(errno.ENOTEMPTY, errno.EEXIST):
with ctx.suppress_oserror(errno.ENOTEMPTY, errno.EEXIST):
os.rename(self._tree, destination)
self.reset()