Unverified Commit bc283903 authored by Philipp Sommer's avatar Philipp Sommer
Browse files

add a PrintReport

parent 3cf5300b
from ._version import get_versions
from .progress_report import BaseReport, ProgressReport # noqa: F401
from .progress_report import ( # noqa: F401
BaseReport,
PrintReport,
ProgressReport,
)
__version__ = get_versions()["version"]
del get_versions
......@@ -74,6 +74,12 @@ class BaseReport(BaseModel):
@property
def window(self) -> curses.window: # type: ignore
"""A curses window for displaying the report.
See Also
--------
show_curses
"""
if self._window is None:
self._window = curses.initscr()
return self._window
......@@ -130,11 +136,12 @@ class BaseReport(BaseModel):
self.show_curses()
def show_print(self):
print(self.report_as_string())
"""Show the report using pythons built-in :func:`print` function."""
print(self.report_to_string())
def show_curses(self):
"""Update the :attr:`window`."""
report = self.report_as_string()
"""Show the report using pythons built-in :func:`curses` module."""
report = self.report_to_string()
height, width = self.window.getmaxyx()
lines = report.splitlines()[-height + 1 :]
report = "\n".join([line[: width - 1] for line in lines])
......@@ -144,9 +151,20 @@ class BaseReport(BaseModel):
self.window.refresh()
def report_to_string(self) -> str:
"""Render the report as a string."""
return self.json(indent=2)
def complete(self, status: Status = Status.SUCCESS):
"""Mark the report as complete.
This method marks the report as complete and closes eventually created
widgets or curses windows.
Parameters
----------
status : Status, optional
[description], by default Status.SUCCESS
"""
self.status = status
self.submit()
if self._window is not None:
......@@ -183,12 +201,33 @@ class ProgressReport(BaseReport):
_parent: Optional[ProgressReport] = None
def submit(self):
# reimplemented to use the parents submit method if there is a parent.
if self._parent is not None:
self._parent.submit()
else:
super().submit()
submit.__doc__ = BaseReport.submit.__doc__
def create_subreport(self, *args, **kwargs):
"""Create a child subreport.
This method creates a new subreport and registers it as a child.
Parameters are the same as for the :class:`ProgressReport`.
Parameters
----------
submit: Optional[bool]
Keyword-only argument. If True (default False), submit the child
report.
``*args, **kwargs``
The same as for the :class:`ProgressReport`
Returns
-------
ProgressReport
The child report that has been created.
"""
submit = kwargs.pop("submit", False)
child = ProgressReport(*args, **kwargs)
child._parent = self
......@@ -199,3 +238,62 @@ class ProgressReport(BaseReport):
ProgressReport.update_forward_refs()
class PrintReport(BaseReport):
"""A simple report to print a statement."""
report_type: Literal["print"] = Field( # type: ignore
"print", description="Selector for the report type."
)
messages: List[str] = Field(
default_factory=list, description="The message to print."
)
def report_to_string(self) -> str:
return "\n".join(self.messages).rstrip()
def show_print(self) -> None:
"""Only print the last message."""
print(self.messages[-1])
def show(self) -> None:
"""Reimplement to only show the report when it's complete."""
if self.messages:
if self.status != Status.SUCCESS or self.messages[-1]:
return super().show()
def print(self, message: str) -> None:
"""Update the report and show the message."""
self.messages.append(message)
self.status = Status.RUNNING
self.submit()
def error(self, message: str) -> None:
"""Display an error message."""
self.messages.append(message)
self.status = Status.ERROR
self.submit()
def complete(
self, status: Status = Status.SUCCESS, message: str = ""
) -> None:
"""Mark the report as complete.
This method marks the report as complete and closes eventually created
widgets or curses windows. You can submit an additional message that
will then be added to the report.
Parameters
----------
status : Status, optional
[description], by default Status.SUCCESS
"""
self.messages.append(message)
return super().complete(status=status)
def __exit__(self, exc_type, exc_value, exc_tb):
if exc_value is not None:
self.messages.append(str(exc_value))
return super().__exit__(exc_type, exc_value, exc_tb)
import time
if __name__ == "__main__":
from deprogressapi import ProgressReport
from deprogressapi import PrintReport, ProgressReport
# create the root report
with ProgressReport(step_message="Init", steps=2) as pr1:
time.sleep(1)
# create a sub report
with pr1.create_subreport(
step_message="Step 1.1 - Download"
) as pr1_sub1:
# run the corresponding task ...
time.sleep(1)
with pr1.create_subreport(
step_message="Step 1.2 - Process Download", steps=2
) as pr1_sub2:
......@@ -27,9 +25,14 @@ if __name__ == "__main__":
)
time.sleep(1)
pr1_sub21.complete()
with pr1_sub2.create_subreport(
step_message="Step 1.2.2 - Process Download"
) as pr1_sub22:
time.sleep(1)
time.sleep(1)
with PrintReport() as report:
report.print("This is just a simple statement that will be printed!")
time.sleep(1)
report.error("This indicates that an error has happened")
time.sleep(1)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment