build.lib.util, build.App: Beautify exceptions

Make exceptions somewhat more readable.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2025-11-20 10:44:14 +01:00
commit 150bc97fc9
2 changed files with 20 additions and 8 deletions

View file

@ -458,4 +458,9 @@ class App(object):
subparser = argparse.ArgumentParser(description=cmd_name)
cmd.add_arguments(subparser)
args = subparser.parse_args(sys.argv[(len(self.global_args) + 1)::])
return cmd.run(args)
try:
return cmd.run(args)
except Exception as e:
self.err('Failed to run >{}<: {}'.format(' '.join(sys.argv), e))
raise
sys.exit(1)

View file

@ -4,19 +4,22 @@ import os, sys, subprocess, json, time
from argparse import Namespace
from urllib.parse import urlparse
def run_cmd(cmd: list[str], wd=None, throw=True, verbose=False) -> str|None: # export
def pretty_cmd(cmd: list[str], wd=None):
tokens = [cmd[0]]
for token in cmd[1:]:
if token.find(' ') != -1:
token = '"' + token + '"'
tokens.append(token)
subject = ' '.join(tokens)
ret = ' '.join(tokens)
if wd is not None:
subject += f' in {wd}'
ret += f' in {wd}'
return ret
def run_cmd(cmd: list[str], wd=None, throw=True, verbose=False) -> str|None: # export
if verbose:
delim_len = 120
delim = f'---- running {subject} -'
delim = f'---- running {pretty_cmd(cmd, wd)} -'
delim = delim + '-' * (delim_len - len(delim))
print(',' + delim + ' >')
@ -37,7 +40,7 @@ def run_cmd(cmd: list[str], wd=None, throw=True, verbose=False) -> str|None: # e
if p.returncode:
if verbose:
print(' '.join(cmd) + ' failed')
raise Exception(time.strftime('%Y-%m-%d %H:%M') + f': failed to run "{subject}"')
raise Exception(time.strftime('%Y-%m-%d %H:%M') + f': Command returned an error: "{pretty_cmd(cmd, wd)}"')
finally:
if cwd:
os.chdir(cwd)
@ -50,7 +53,11 @@ def run_curl(args: list[str], parse_json: bool=True, wd=None, throw=None, verbos
cmd.extend(args)
ret = run_cmd(cmd, wd=wd, throw=throw, verbose=verbose)
if parse_json:
return json.loads(ret)
try:
return json.loads(ret)
except Exception as e:
print(f'Failed to parse {len(ret)} bytes output of command >{pretty_cmd(cmd, wd)}< ({e})', file=sys.stderr)
raise
return ret
def get_username(args: Namespace|None=None, url: str|None=None) -> str: # export