From: Zbigniew Jędrzejewski-Szmek Date: Tue, 13 Sep 2022 15:58:13 +0000 (+0100) Subject: code: split out the handling of exceptions to a helper X-Git-Tag: v14~5 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=3dc6aa69303321b78c3e6cd84b77d53c00b72ddb;p=thirdparty%2Fmkosi.git code: split out the handling of exceptions to a helper This is a bit of error-handling logic that shouldn't obscure the main logic of the program. --- diff --git a/mkosi/__main__.py b/mkosi/__main__.py index 46eaccb2d..8c84cc63e 100644 --- a/mkosi/__main__.py +++ b/mkosi/__main__.py @@ -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()