Skip to content

Commit

Permalink
rename Printer to Formatter
Browse files Browse the repository at this point in the history
* remove print_* functions
  • Loading branch information
agoscinski committed Dec 25, 2023
1 parent 356cb6d commit 4732b34
Show file tree
Hide file tree
Showing 6 changed files with 81 additions and 78 deletions.
36 changes: 13 additions & 23 deletions src/scwidgets/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,54 +3,44 @@
from termcolor import colored


class Printer:
# TODO rename to Formatter
# remove print funcs
class Formatter:
LINE_LENGTH = 120
INFO_COLOR = "blue"
ERROR_COLOR = "red"
SUCCESS_COLOR = "green"

@staticmethod
def format_title_message(message: str) -> str:
return message.center(Printer.LINE_LENGTH - len(message) // 2, "-")
return message.center(Formatter.LINE_LENGTH - len(message) // 2, "-")

@staticmethod
def break_lines(message: str) -> str:
return "\n ".join(re.findall(r".{1," + str(Printer.LINE_LENGTH) + "}", message))
return "\n ".join(
re.findall(r".{1," + str(Formatter.LINE_LENGTH) + "}", message)
)

@staticmethod
def color_error_message(message: str) -> str:
return colored(message, Printer.ERROR_COLOR, attrs=["bold"])

@staticmethod
def print_error_message(message: str):
print(Printer.color_error_message(message))
return colored(message, Formatter.ERROR_COLOR, attrs=["bold"])

@staticmethod
def color_success_message(message: str) -> str:
return colored(message, Printer.SUCCESS_COLOR, attrs=["bold"])

@staticmethod
def print_success_message(message: str):
print(Printer.color_success_message(message))
return colored(message, Formatter.SUCCESS_COLOR, attrs=["bold"])
print(Formatter.color_success_message(message))

@staticmethod
def color_info_message(message: str):
return colored(message, Printer.INFO_COLOR, attrs=["bold"])

@staticmethod
def print_info_message(message: str):
print(Printer.color_info_message(message))
return colored(message, Formatter.INFO_COLOR, attrs=["bold"])
print(Formatter.color_info_message(message))

@staticmethod
def color_assert_failed(message: str) -> str:
return colored(message, "light_" + Printer.ERROR_COLOR)
return colored(message, "light_" + Formatter.ERROR_COLOR)

@staticmethod
def color_assert_info(message: str) -> str:
return colored(message, "light_" + Printer.INFO_COLOR)
return colored(message, "light_" + Formatter.INFO_COLOR)

@staticmethod
def color_assert_success(message: str) -> str:
return colored(message, "light_" + Printer.SUCCESS_COLOR)
return colored(message, "light_" + Formatter.SUCCESS_COLOR)
18 changes: 10 additions & 8 deletions src/scwidgets/answer/_widget_answer_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from IPython.display import display
from ipywidgets import Button, Dropdown, HBox, Label, Layout, Output, Text, VBox

from .._utils import Printer
from .._utils import Formatter


class AnswerWidget:
Expand Down Expand Up @@ -456,9 +456,9 @@ def _on_click_confirm_save_button(self, change: dict):
with self._output:
try:
message = self.save_all_answers()
Printer.print_success_message(message)
print(Formatter.color_success_message(message))
except Exception as exception:
Printer.print_error_message("Error raised while saving file:")
print(Formatter.color_error_message("Error raised while saving file:"))
raise exception

def _on_click_choose_other_file_button(self, change: dict):
Expand All @@ -479,9 +479,9 @@ def _on_click_load_file_button(self, change: dict):
self._disable_upper_panel_box()
self._enable_lower_panel_box()
self._show_lower_panel_box()
Printer.print_success_message(result)
print(Formatter.color_success_message(result))
except Exception as exception:
Printer.print_error_message("Error raised while loading file:")
print(Formatter.color_error_message("Error raised while loading file:"))
raise exception

def _on_answers_files_dropdown_value_changed(self, change: dict):
Expand All @@ -504,9 +504,11 @@ def _on_click_confirm_create_new_file_button(self, change: dict):
with self._output:
try:
result = self.create_new_file()
Printer.print_success_message(result)
print(Formatter.color_success_message(result))
except Exception as exception:
Printer.print_error_message("Error raised while creating file:")
print(
Formatter.color_error_message("Error raised while creating file:")
)
raise exception

def _on_click_cancel_save_button(self, change: dict):
Expand All @@ -516,7 +518,7 @@ def _on_click_save_all_answers_button(self, change: dict):
self._output.clear_output(wait=True)
with self._output:
display(self._confirmation_button_box)
Printer.print_info_message("Are you sure?")
print(Formatter.color_info_message("Are you sure?"))

#####################
# private functions #
Expand Down
27 changes: 14 additions & 13 deletions src/scwidgets/check/_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import IPython.core.ultratb

from .._utils import Printer
from .._utils import Formatter

ExecutionInfo = Tuple[
Union[None, type], # BaseException type
Expand Down Expand Up @@ -312,23 +312,24 @@ def message(self) -> str:
if (isinstance(result, str) and result == "") or (
isinstance(result, AssertResult) and result.successful
):
message = Printer.color_assert_success(
message = Formatter.color_assert_success(
f"{self._assert_names[i]} passed",
)
else:
message = Printer.color_assert_failed(
message = Formatter.color_assert_failed(
f"{self._assert_names[i]} failed",
)
if len(self._inputs_parameters[i]) > 0:
message += Printer.color_error_message(" for input\n")
message += Formatter.color_error_message(" for input\n")
elif (isinstance(result, tuple) and len(result) == 3) or not (
self._suppress_assert_messages[i]
):
message += Printer.color_error_message("\n")
message += Formatter.color_error_message("\n")

message += "\n".join(
[
f" {Printer.color_info_message(param_name)}: {param_value!r}"
f" {Formatter.color_info_message(param_name)}: "
f"{param_value!r}"
for param_name, param_value in self._inputs_parameters[
i
].items()
Expand All @@ -339,13 +340,13 @@ def message(self) -> str:
if len(self._inputs_parameters[i]) > 0:
message += "\n"
tb = IPython.core.ultratb.VerboseTB()
message = Printer.color_assert_failed(
message = Formatter.color_assert_failed(
f"{self._assert_names[i]} failed\n"
)
assert_result = tb.text(*result)
assert_result = re.sub(
r"(^)",
r"\1" + f"{Printer.color_assert_failed('|')} ",
r"\1" + f"{Formatter.color_assert_failed('|')} ",
assert_result,
flags=re.M,
)
Expand All @@ -356,11 +357,11 @@ def message(self) -> str:
if hasattr(result, "message"):
assert_result = f"{result.message()}"
else:
assert_result = f"{Printer.color_assert_failed(result)}"
assert_result = f"{Formatter.color_assert_failed(result)}"
# adds "| " to the beginning of each line
assert_result = re.sub(
r"(^)",
r"\1" + f"{Printer.color_assert_failed('|')} ",
r"\1" + f"{Formatter.color_assert_failed('|')} ",
assert_result,
flags=re.M,
)
Expand Down Expand Up @@ -446,9 +447,9 @@ def message(self) -> str:
message = ""
for i in range(len(self._parameter_indices)):
message += (
Printer.color_assert_failed(f"output {self._parameter_indices[i]}: ")
+ Printer.color_assert_failed(f"{self._parameter_values[i]}\n")
+ Printer.color_assert_failed(self._messages[i])
Formatter.color_assert_failed(f"output {self._parameter_indices[i]}: ")
+ Formatter.color_assert_failed(f"{self._parameter_values[i]}\n")
+ Formatter.color_assert_failed(self._messages[i])
)
return message

Expand Down
38 changes: 24 additions & 14 deletions src/scwidgets/check/_widget_check_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from ipywidgets import Button, HBox, Layout, Output, VBox, Widget

from .._utils import Printer
from .._utils import Formatter
from ._check import Check, ChecksLog


Expand Down Expand Up @@ -264,7 +264,7 @@ def _on_click_set_all_references_button(self, change: dict):
self._output.clear_output(wait=True)
with self._output:
self.compute_and_set_all_references()
Printer.print_success_message("Successfully set all references.")
print(Formatter.color_success_message("Successfully set all references."))

def _on_click_check_all_widgets_button(self, change: dict):
self._output.clear_output(wait=True)
Expand All @@ -277,26 +277,32 @@ def _on_click_check_all_widgets_button(self, change: dict):
for widget, widget_results in widgets_results.items():
with self._output:
if isinstance(widget_results, Exception):
Printer.print_error_message(
Printer.format_title_message(
f"Widget {self._names[widget]} " f"raised error:"
print(
Formatter.color_error_message(
Formatter.format_title_message(
f"Widget {self._names[widget]} " f"raised error:"
)
)
)
raise widget_results
elif isinstance(widget_results, ChecksLog):
if widget_results.successful:
Printer.print_success_message(
Printer.format_title_message(
f"Widget {self._names[widget]} all checks "
f"were successful"
print(
Formatter.color_success_message(
Formatter.format_title_message(
f"Widget {self._names[widget]} all checks "
f"were successful"
)
)
)
print(widget_results.message())
else:
Printer.print_error_message(
Printer.format_title_message(
f"Widget {self._names[widget]} not all checks were "
"successful:"
print(
Formatter.color_error_message(
Formatter.format_title_message(
f"Widget {self._names[widget]} not all checks "
"were successful:"
)
)
)
print(widget_results.message())
Expand All @@ -308,5 +314,9 @@ def _on_click_check_all_widgets_button(self, change: dict):
)
except Exception as exception:
with self._output:
Printer.print_error_message("Error raised while checking widgets:")
print(
Formatter.color_error_message(
"Error raised while checking widgets:"
)
)
raise exception
22 changes: 11 additions & 11 deletions src/scwidgets/code/_widget_code_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from ipywidgets import HTML, Box, HBox, HTMLMath, Layout, VBox, Widget
from widget_code_input.utils import CodeValidationError

from .._utils import Printer
from .._utils import Formatter
from ..answer import AnswerRegistry, AnswerWidget
from ..check import Check, CheckableWidget, CheckRegistry, ChecksLog
from ..cue import (
Expand Down Expand Up @@ -521,14 +521,14 @@ def _on_click_save_action(self) -> bool:
try:
result = self.save()
if isinstance(result, str):
Printer.print_success_message(result)
print(Formatter.color_success_message(result))
elif isinstance(result, Exception):
raise result
else:
print(result)
except Exception as e:
raised_error = True
Printer.print_error_message("Error raised while saving file:")
print(Formatter.color_error_message("Error raised while saving file:"))
raise e
return not (raised_error)

Expand All @@ -539,14 +539,14 @@ def _on_click_load_action(self) -> bool:
try:
result = self.load()
if isinstance(result, str):
Printer.print_success_message(result)
print(Formatter.color_success_message(result))
elif isinstance(result, Exception):
raise result
else:
print(result)
except Exception as e:
raised_error = True
Printer.print_error_message("Error raised while loading file:")
print(Formatter.color_error_message("Error raised while loading file:"))
raise e
return not (raised_error)

Expand All @@ -564,12 +564,12 @@ def handle_checks_result(self, result: Union[ChecksLog, Exception]):
raise result
elif isinstance(result, ChecksLog):
if result.successful:
Printer.print_success_message("Check was successful")
Printer.print_success_message("--------------------")
print(Formatter.color_success_message("Check was successful"))
print(Formatter.color_success_message("--------------------"))
print(result.message())
else:
Printer.print_error_message("Check failed")
Printer.print_error_message("------------")
print(Formatter.color_error_message("Check failed"))
print(Formatter.color_error_message("------------"))
print(result.message())
else:
print(result)
Expand All @@ -586,7 +586,7 @@ def handle_save_result(self, result: Union[str, Exception]):
self._save_button.cued = False
if self._save_cue_box is not None:
self._save_cue_box.cued = False
Printer.print_success_message(result)
print(Formatter.color_success_message(result))

def handle_load_result(self, result: Union[str, Exception]):
self._output.clear_output(wait=True)
Expand All @@ -600,7 +600,7 @@ def handle_load_result(self, result: Union[str, Exception]):
self._save_button.cued = False
if self._save_cue_box is not None:
self._save_cue_box.cued = False
Printer.print_success_message(result)
print(Formatter.color_success_message(result))

@property
def code(self):
Expand Down
Loading

0 comments on commit 4732b34

Please sign in to comment.