]> git.ipfire.org Git - thirdparty/mkosi.git/commitdiff
Tweak exception handling 1491/head
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Sun, 23 Apr 2023 13:47:38 +0000 (15:47 +0200)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Mon, 24 Apr 2023 19:00:37 +0000 (21:00 +0200)
- Remove optional exception argument of die() in favor of just using
  logging.error() and re-raising the exception
- Instead of raising RuntimeError in die(), just call sys.exit()
  instead which raises SystemExit.
- Show stacktrace of every exception that isn't SystemExit,
  KeyboardInterrupt or subprocess.CalledProcessError.

mkosi/__main__.py
mkosi/log.py
mkosi/run.py
tests/test_parse_load_args.py

index 91a4f159bf62728669401fe4e11bf55efb86ed9c..fd8884f4ccdc619f861805aec24cc2b2bc6e183a 100644 (file)
@@ -37,14 +37,6 @@ def propagate_failed_return() -> Iterator[None]:
 
         # We always log when subprocess.CalledProcessError is raised, so we don't log again here.
         sys.exit(e.returncode)
-    except Exception as e:
-        if ARG_DEBUG.get():
-            raise e
-        elif not isinstance(e, RuntimeError):
-            # RuntimeError is used to wrap generic errors, and the message that was printed should be enough.
-            logging.info(f"Hint: mkosi failed because of an internal exception {e.__class__.__name__}, "
-                          "rerun mkosi with --debug to get more information")
-        sys.exit(1)
 
 
 @propagate_failed_return()
index 9f11370bd31725d4dae7b459d5f3ab4363aceb12..8cdfef70e8488888c399041f53f9e2a2b30abd29 100644 (file)
@@ -20,13 +20,12 @@ class Style:
 
 
 def die(message: str,
-        exception: Optional[Exception] = None,
         *,
         hint: Optional[str] = None) -> NoReturn:
     logging.error(f"{message}")
     if hint:
         logging.info(f"({hint})")
-    raise exception or RuntimeError(message)
+    sys.exit(1)
 
 
 def color_error(text: Any) -> str:
index 6be3bb0288d1360086b635dbf184c785f9c1fe93..aaa0b0135b1c0c5c03ad54efbcd62975afffc2b9 100644 (file)
@@ -238,11 +238,11 @@ def run(
                               env=env,
                               **kwargs,
                               preexec_fn=foreground)
-    except FileNotFoundError as e:
-        die(f"{cmdline[0]} not found in PATH.", e)
+    except FileNotFoundError:
+        die(f"{cmdline[0]} not found in PATH.")
     except subprocess.CalledProcessError as e:
         if log:
-            die(f'"{shlex.join(str(s) for s in cmdline)}" returned non-zero exit code {e.returncode}.', e)
+            logging.error(f'"{shlex.join(str(s) for s in cmdline)}" returned non-zero exit code {e.returncode}.')
         raise e
 
 
@@ -266,7 +266,8 @@ def spawn(
     except FileNotFoundError:
         die(f"{cmdline[0]} not found in PATH.")
     except subprocess.CalledProcessError as e:
-        die(f'"{shlex.join(str(s) for s in cmdline)}" returned non-zero exit code {e.returncode}.', e)
+        logging.error(f'"{shlex.join(str(s) for s in cmdline)}" returned non-zero exit code {e.returncode}.')
+        raise e
 
 
 def bwrap(
@@ -321,9 +322,10 @@ def bwrap(
             return run([*cmdline, template.format(shlex.join(str(s) for s in cmd))],
                        text=True, stdout=stdout, env=env, log=False)
         except subprocess.CalledProcessError as e:
+            logging.error(f'"{shlex.join(str(s) for s in cmd)}" returned non-zero exit code {e.returncode}.')
             if ARG_DEBUG_SHELL.get():
                 run([*cmdline, template.format("sh")], stdin=sys.stdin, check=False, env=env, log=False)
-            die(f'"{shlex.join(str(s) for s in cmd)}" returned non-zero exit code {e.returncode}.')
+            raise e
 
 
 def run_workspace_command(
@@ -382,9 +384,10 @@ def run_workspace_command(
             return run([*cmdline, template.format(shlex.join(str(s) for s in cmd))],
                        text=True, stdout=stdout, env=env, log=False)
         except subprocess.CalledProcessError as e:
+            logging.error(f'"{shlex.join(str(s) for s in cmd)}" returned non-zero exit code {e.returncode}.')
             if ARG_DEBUG_SHELL.get():
                 run([*cmdline, template.format("sh")], stdin=sys.stdin, check=False, env=env, log=False)
-            die(f'"{shlex.join(str(s) for s in cmd)}" returned non-zero exit code {e.returncode}.')
+            raise e
         finally:
             if tmp.is_symlink():
                 resolve.unlink(missing_ok=True)
index 9a06e66ff2d65cd13ba035b80fb4c73b7c5dc6a5..4a5e737f0cfc08eef0df9d46b843afc140a5236f 100644 (file)
@@ -75,13 +75,13 @@ def test_parse_config_files_filter() -> None:
 
 def test_shell_boot() -> None:
     with cd_temp_dir():
-        with pytest.raises(RuntimeError, match=".boot.*tar"):
+        with pytest.raises(SystemExit):
             parse(["--format", "tar", "boot"])
 
-        with pytest.raises(RuntimeError, match=".boot.*cpio"):
+        with pytest.raises(SystemExit):
             parse(["--format", "cpio", "boot"])
 
-        with pytest.raises(RuntimeError, match=".boot.*compressed" ):
+        with pytest.raises(SystemExit):
             parse(["--format", "disk", "--compress-output=yes", "boot"])