]> git.ipfire.org Git - thirdparty/mkosi.git/commitdiff
code: split out the handling of exceptions to a helper
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Tue, 13 Sep 2022 15:58:13 +0000 (16:58 +0100)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Thu, 27 Oct 2022 08:07:12 +0000 (10:07 +0200)
This is a bit of error-handling logic that shouldn't obscure the
main logic of the program.

mkosi/__main__.py

index 46eaccb2da0ded3c56ebd09e7e00efeb9e052068..8c84cc63e92b5783bbfc267b0b9bda7d94deee48 100644 (file)
@@ -1,30 +1,20 @@
 # SPDX-License-Identifier: LGPL-2.1+
 # PYTHON_ARGCOMPLETE_OK
+
+import contextlib
 import os
 import sys
 from subprocess import CalledProcessError
+from typing import Iterator
 
 from . import complete_step, parse_args, run_verb
 from .backend import MkosiException, die
 
 
-def main() -> None:
+@contextlib.contextmanager
+def propagate_failed_return() -> Iterator[None]:
     try:
-        args = parse_args()
-
-        for job_name, a in args.items():
-            # Change working directory if --directory is passed
-            if a.directory:
-                work_dir = a.directory
-                if os.path.isdir(work_dir):
-                    os.chdir(work_dir)
-                else:
-                    die(f"Error: {work_dir} is not a directory!")
-            if len(args) > 1:
-                with complete_step(f"Processing {job_name}"):
-                    run_verb(a)
-            else:
-                run_verb(a)
+        yield
     except MkosiException as e:
         cause = e.__cause__
         if cause and isinstance(cause, CalledProcessError):
@@ -32,5 +22,24 @@ def main() -> None:
         sys.exit(1)
 
 
+@propagate_failed_return()
+def main() -> None:
+    args = parse_args()
+
+    for job_name, a in args.items():
+        # Change working directory if --directory is passed
+        if a.directory:
+            work_dir = a.directory
+            if os.path.isdir(work_dir):
+                os.chdir(work_dir)
+            else:
+                die(f"Error: {work_dir} is not a directory!")
+        if len(args) > 1:
+            with complete_step(f"Processing {job_name}"):
+                run_verb(a)
+        else:
+            run_verb(a)
+
+
 if __name__ == "__main__":
     main()