clean up print_msgs function

This commit is contained in:
Jonathan Wren 2022-05-17 12:04:24 -07:00
parent 13b1046a05
commit 70157303d4
6 changed files with 81 additions and 85 deletions

View file

@ -49,7 +49,7 @@ def cli(manual_args=None):
print_msg( print_msg(
Message( Message(
MsgText.KeyboardInterruptMsg, MsgText.KeyboardInterruptMsg,
MsgStyle.ERROR, MsgStyle.ERROR_ON_NEW_LINE,
) )
) )

View file

@ -66,7 +66,7 @@ def get_text_from_stdin():
except KeyboardInterrupt: except KeyboardInterrupt:
logging.error("Write mode: keyboard interrupt") logging.error("Write mode: keyboard interrupt")
raise JrnlException( raise JrnlException(
Message(MsgText.KeyboardInterruptMsg, MsgStyle.ERROR), Message(MsgText.KeyboardInterruptMsg, MsgStyle.ERROR_ON_NEW_LINE),
Message(MsgText.JournalNotSaved, MsgStyle.WARNING), Message(MsgText.JournalNotSaved, MsgStyle.WARNING),
) )

View file

@ -44,45 +44,6 @@ class MsgDecoration(Enum):
return self.value["args"] return self.value["args"]
class MsgStyle(Enum):
BARE = {
"decoration": MsgDecoration.NONE,
"color": _MsgColor("white"),
}
PLAIN = {
"decoration": MsgDecoration.BRACKET,
"color": _MsgColor("white"),
}
PROMPT = {
"decoration": MsgDecoration.NONE,
"color": _MsgColor("white"),
}
TITLE = {
"decoration": MsgDecoration.BOX,
"color": _MsgColor("cyan"),
}
NORMAL = {
"decoration": MsgDecoration.BOX,
"color": _MsgColor("white"),
}
WARNING = {
"decoration": MsgDecoration.BOX,
"color": _MsgColor("yellow"),
}
ERROR = {
"decoration": MsgDecoration.BOX,
"color": _MsgColor("red"),
}
@property
def decoration(self) -> MsgDecoration:
return self.value["decoration"]
@property
def color(self) -> _MsgColor:
return self.value["color"].color
class MsgText(Enum): class MsgText(Enum):
def __str__(self) -> str: def __str__(self) -> str:
return self.value return self.value
@ -122,6 +83,7 @@ class MsgText(Enum):
OneCharacterNo = "n" OneCharacterNo = "n"
# --- Exceptions ---# # --- Exceptions ---#
Error = "Error"
UncaughtException = """ UncaughtException = """
{name} {name}
{exception} {exception}
@ -320,6 +282,65 @@ class MsgText(Enum):
""" """
class MsgStyle(Enum):
BARE = {
"decoration": MsgDecoration.NONE,
"color": _MsgColor("white"),
}
PLAIN = {
"decoration": MsgDecoration.BRACKET,
"color": _MsgColor("white"),
}
PROMPT = {
"decoration": MsgDecoration.NONE,
"color": _MsgColor("white"),
"append_space": True,
}
TITLE = {
"decoration": MsgDecoration.BOX,
"color": _MsgColor("cyan"),
}
NORMAL = {
"decoration": MsgDecoration.BOX,
"color": _MsgColor("white"),
}
WARNING = {
"decoration": MsgDecoration.BOX,
"color": _MsgColor("yellow"),
}
ERROR = {
"decoration": MsgDecoration.BOX,
"color": _MsgColor("red"),
"box_title": str(MsgText.Error),
}
ERROR_ON_NEW_LINE = {
"decoration": MsgDecoration.BOX,
"color": _MsgColor("red"),
"prepend_newline": True,
"box_title": str(MsgText.Error),
}
@property
def decoration(self) -> MsgDecoration:
return self.value["decoration"]
@property
def color(self) -> _MsgColor:
return self.value["color"].color
@property
def prepend_newline(self) -> bool:
return self.value.get("prepend_newline", False)
@property
def append_space(self) -> bool:
return self.value.get("append_space", False)
@property
def box_title(self) -> MsgText:
return self.value.get("box_title", None)
class Message(NamedTuple): class Message(NamedTuple):
text: MsgText text: MsgText
style: MsgStyle = MsgStyle.NORMAL style: MsgStyle = MsgStyle.NORMAL

View file

@ -39,74 +39,49 @@ def list_journals(configuration):
return result return result
def print_msg(msg: Message, is_prompt: bool = False) -> Union[None, str]: def print_msg(msg: Message) -> Union[None, str]:
return print_msgs([msg], style=msg.style, is_prompt=is_prompt) """Helper function to print a single message"""
return print_msgs([msg], style=msg.style)
def print_msgs( def print_msgs(
msgs: list[Message], msgs: list[Message],
delimiter: str = "\n", delimiter: str = "\n",
style: MsgStyle = MsgStyle.NORMAL, style: MsgStyle = MsgStyle.NORMAL,
is_prompt: bool = False, get_input: bool = False,
) -> Union[None, str]: ) -> Union[None, str]:
# Same as print_msg, but for a list # Same as print_msg, but for a list
text = Text("") text = Text("", end="")
decoration_callback = style.decoration.callback kwargs = style.decoration.args
args = style.decoration.args
prepend_newline = False
append_space = False
for msg in msgs: for i, msg in enumerate(msgs):
args = _add_extra_style_args_if_needed(args, msg=msg) kwargs = _add_extra_style_args_if_needed(kwargs, msg=msg)
if _needs_prepended_newline(msg):
prepend_newline = True
if _needs_appended_space(msg):
append_space = True
m = format_msg_text(msg) m = format_msg_text(msg)
m.append(delimiter)
if i != len(msgs) - 1:
m.append(delimiter)
text.append(m) text.append(m)
text.rstrip() if style.append_space:
if append_space:
text.append(" ") text.append(" ")
decorated_text = style.decoration.callback(text, **kwargs)
# Always print messages to stderr # Always print messages to stderr
console = Console(stderr=True) console = Console(stderr=True)
decorated_text = decoration_callback(text, **args) if get_input:
if is_prompt:
return str(console.input(prompt=decorated_text)) return str(console.input(prompt=decorated_text))
else: console.print(decorated_text, new_line_start=style.prepend_newline)
console.print(decorated_text, new_line_start=prepend_newline)
def _add_extra_style_args_if_needed(args, msg): def _add_extra_style_args_if_needed(args, msg):
args["border_style"] = msg.style.color args["border_style"] = msg.style.color
args["title"] = "Error" if msg.style == MsgStyle.ERROR else None args["title"] = msg.style.box_title
return args return args
def _needs_prepended_newline(msg: Message) -> bool:
return is_keyboard_int(msg)
def _needs_appended_space(msg: Message) -> bool:
return is_prompt(msg)
def is_prompt(msg: Message) -> bool:
return msg.style == MsgStyle.PROMPT
def is_keyboard_int(msg: Message) -> bool:
return msg.text == MsgText.KeyboardInterruptMsg
def format_msg_text(msg: Message) -> Text: def format_msg_text(msg: Message) -> Text:
text = textwrap.dedent(msg.text.value.format(**msg.params)).strip() text = textwrap.dedent(msg.text.value.format(**msg.params)).strip()
return Text(text) return Text(text)

View file

@ -29,7 +29,7 @@ class JRNLImporter:
other_journal_txt = sys.stdin.read() other_journal_txt = sys.stdin.read()
except KeyboardInterrupt: except KeyboardInterrupt:
raise JrnlException( raise JrnlException(
Message(MsgText.KeyboardInterruptMsg, MsgStyle.ERROR), Message(MsgText.KeyboardInterruptMsg, MsgStyle.ERROR_ON_NEW_LINE),
Message(MsgText.ImportAborted, MsgStyle.WARNING), Message(MsgText.ImportAborted, MsgStyle.WARNING),
) )

View file

@ -40,7 +40,7 @@ def yesno(prompt: Message, default: bool = True) -> bool:
], ],
style=MsgStyle.PROMPT, style=MsgStyle.PROMPT,
delimiter=" ", delimiter=" ",
is_prompt=True, get_input=True,
) )
answers = { answers = {