Watch
1
0
Fork
You've already forked git-lad
0
forked from datalad/git-lad
git-lad/git_lad/exceptions/__init__.py
Michael Hanke 04dff9b320
chore: switch from deprecated getdefaultlocale() to getpreferredencoding()
The former was deprecated in Python 3.11, which is the minimum supported
version here. The latter has been present in Python 3 forever.
2026-06-05 08:11:12 +02:00

98 lines
2.8 KiB
Python

"""Utilities for exception handling"""
__all__ = [
'cmderror2richtext',
]
from locale import getpreferredencoding
from datasalad.runners import CommandError
from rich.console import Group
from rich.panel import Panel
from rich.rule import Rule
from rich.text import Text
_default_locale = getpreferredencoding(False)
def _cmd2renderable(cmd: list):
# we use a dedicated symbol to visualize the boundary between
# distinct args to avoid quotation overkill, which will also be
# hard to get right in a cross-platform context.
# the idea is to use simple `space`, but style it to look like
# a connector, to visualize the boundary, but avoid an artifact
# when copying
segment_connector = Text(' ', style='underline blue')
out = Text()
out.append(cmd[0], style='')
for seg in cmd[1:]:
out.append(segment_connector)
# str() in order to deal with stuff like Path() objects
out.append(Text(str(seg), style=''))
return out
def _decode_output(txt: bytes | str) -> str:
if not isinstance(txt, bytes):
# on some platforms we will get `str` immediately
return txt
return txt.decode(_default_locale)
def _err_rule(title):
return Rule(
title=Text(title, style='red'),
style='red',
align='left',
)
def cmderror2richtext(err: CommandError):
# the order of reporting is significant mand intentional
# 1. any generic and tailored message available on the error, to set
# the broad context for understanding what is going on
# 2. the command that errored, required to understand the output
# that was captured
# 3. captured stdout
# 4. captured stderr
#
# stderr is shown last, because it will be closest to the user's
# attention in a terminal. With a sensible command, and a characteristic
# error message, this information on its own may already be enough
# for a user to understand what happened.
msg = Text('A command errored unexpectedly')
if err.returncode:
msg.append(Text(f' with exitcode {err.returncode}'))
if err.cwd:
msg.append(Text(f' in {err.cwd}'))
msg.append('.')
if err.msg:
msg.append(f' {err.msg}')
items = [msg]
items.extend(
(
_err_rule('Command'),
_cmd2renderable(err.cmd),
)
)
if err.stdout:
items.extend(
(
_err_rule('Output (stdout)'),
Text(_decode_output(err.stdout)),
)
)
if err.stderr:
items.extend(
(
_err_rule('Error output (stderr)'),
Text(_decode_output(err.stderr)),
)
)
return Panel(
Group(*items),
title='Command execution error',
title_align='left',
border_style='red',
)