forked from datalad/git-lad
84 lines
2.5 KiB
Python
84 lines
2.5 KiB
Python
"""Context manager for providing resource to command implementations"""
|
|
|
|
__all__ = [
|
|
'AnnexNoInitMode',
|
|
'CmdResources',
|
|
'DatasetNoInitMode',
|
|
'ProgressMode',
|
|
'std_option',
|
|
]
|
|
|
|
|
|
import enum
|
|
|
|
import rich
|
|
import rich_click as click
|
|
from datalad_core.services import SerialExecutor
|
|
from datasalad.runners import CommandError
|
|
|
|
from git_lad.exceptions import cmderror2richtext
|
|
from git_lad.progress import RichProgressHandler
|
|
|
|
from .parameters import (
|
|
AnnexNoInitMode,
|
|
DatasetNoInitMode,
|
|
std_option,
|
|
)
|
|
|
|
|
|
class ProgressMode(enum.StrEnum):
|
|
OFF = enum.auto()
|
|
AUTO = enum.auto()
|
|
RICH = enum.auto()
|
|
|
|
|
|
class ResultRenderMode(enum.StrEnum):
|
|
OFF = enum.auto()
|
|
AUTO = enum.auto()
|
|
RICH = enum.auto()
|
|
JSON = enum.auto()
|
|
|
|
|
|
class CmdResources:
|
|
def __init__(
|
|
self,
|
|
progress_mode: ProgressMode,
|
|
result_render_mode: ResultRenderMode,
|
|
):
|
|
self.progress_handler = None
|
|
self.console = None
|
|
self._progress_mode = progress_mode
|
|
self._result_mode = result_render_mode
|
|
self.task_executor = SerialExecutor()
|
|
|
|
def __enter__(self):
|
|
match self._progress_mode:
|
|
case ProgressMode.OFF:
|
|
# we do not create any progress handler
|
|
self.console = rich.console.Console()
|
|
case ProgressMode.RICH:
|
|
self.progress_handler = RichProgressHandler()
|
|
self.console = self.progress_handler.console
|
|
case ProgressMode.AUTO:
|
|
self.console = rich.console.Console()
|
|
if self.console.is_terminal:
|
|
self.progress_handler = RichProgressHandler()
|
|
self.console = self.progress_handler.console
|
|
# TODO: maybe switch to leaner progress logging when False
|
|
# this could be FileIOProgressHandler(sys.stderr)
|
|
return self
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
|
if isinstance(self.progress_handler, RichProgressHandler):
|
|
# TODO: https://hub.datalad.org/datalad/datasalad/issues/71
|
|
self.progress_handler.stop()
|
|
# any CommandError that was raised will come through here
|
|
# we can render it, and signal click to bail out
|
|
# its own language
|
|
if exc_type is CommandError:
|
|
# TODO: support showing a traceback via some kind of option
|
|
# or envvar switch
|
|
msg = cmderror2richtext(exc_value)
|
|
self.console.print(msg)
|
|
raise click.Abort
|
|
return False
|