[elbe-devel] [PATCH v2 3/8] elbepack: imgutils: add mount helper
Thomas Weißschuh
thomas.weissschuh at linutronix.de
Wed May 8 16:03:22 CEST 2024
This helper will automatically clean up mounts via the context manager
protocol.
It will replace open-coded calls to mount(8).
Signed-off-by: Thomas Weißschuh <thomas.weissschuh at linutronix.de>
---
elbepack/imgutils.py | 42 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
diff --git a/elbepack/imgutils.py b/elbepack/imgutils.py
index e74b46bc41f3..d2ea2b669848 100644
--- a/elbepack/imgutils.py
+++ b/elbepack/imgutils.py
@@ -3,6 +3,7 @@
# SPDX-FileCopyrightText: 2024 Linutronix GmbH
import contextlib
+import subprocess
from elbepack.shellhelper import do, get_command_out
@@ -17,3 +18,44 @@ def losetup(dev, extra_args=[]):
yield loopdev
finally:
do(f'losetup --detach {loopdev}', check=False)
+
+
+class _Mount:
+ # This is not using contextlib.contextmanager as it will be pass to our
+ # RPCAPTCache which uses the pickle serialization.
+ # The generator by contextlib.contextmanager is not compatible with pickle.
+ def __init__(self, device, target, *, bind=False, type=None, options=None, log_output=True):
+ self.log_output = log_output
+ self.target = target
+
+ cmd = ['mount']
+ if bind:
+ cmd.append('--bind')
+
+ if options is not None:
+ cmd.extend(['-o', ','.join(options)])
+
+ if type is not None:
+ cmd.extend(['-t', type])
+
+ if device is None:
+ device = 'none'
+
+ cmd.extend([device, target])
+
+ self.cmd = cmd
+
+ def _run_cmd(self, cmd, *args, **kwargs):
+ if self.log_output:
+ do(cmd, *args, **kwargs)
+ else:
+ subprocess.run(cmd, *args, **kwargs)
+
+ def __enter__(self):
+ self._run_cmd(self.cmd)
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self._run_cmd(['umount', self.target], check=False)
+
+
+mount = _Mount
--
2.45.0
More information about the elbe-devel
mailing list