From de872ee7cd7d144ff55feb2d4b0ff01aae5931a5 Mon Sep 17 00:00:00 2001 From: Renan Rodrigo Date: Tue, 24 Sep 2024 20:42:47 -0300 Subject: [PATCH] cli: create superclass for output formatters This eases the isinstance check for Blocks, Tables and whatnot by creating an abstract superclass which represents those, defining to_string in its interface for consistency. Signed-off-by: Renan Rodrigo --- uaclient/cli/formatter.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/uaclient/cli/formatter.py b/uaclient/cli/formatter.py index c7fd9052bf..99304cc2f4 100644 --- a/uaclient/cli/formatter.py +++ b/uaclient/cli/formatter.py @@ -1,3 +1,4 @@ +import abc import os import re import sys @@ -97,7 +98,16 @@ def wrap_text(text: str, max_width: int) -> List[str]: return wrapped_lines -class Table: +class ProOutputFormatter(abc.ABC): + @abc.abstractmethod + def to_string(self, line_length: Optional[int] = None) -> str: + pass + + def __str__(self): + return self.to_string() + + +class Table(ProOutputFormatter): SEPARATOR = " " * 2 def __init__( @@ -148,9 +158,6 @@ def _get_column_sizes(self) -> List[int]: return column_sizes - def __str__(self) -> str: - return self.to_string() - def to_string(self, line_length: Optional[int] = None) -> str: if line_length is None: line_length = _get_default_length() @@ -204,7 +211,7 @@ def _fill_row(self, row: List[str]) -> str: return output -class Block: +class Block(ProOutputFormatter): INDENT_SIZE = 4 INDENT_CHAR = " " @@ -216,9 +223,6 @@ def __init__( self.title = title self.content = content if content is not None else [] - def __str__(self) -> str: - return self.to_string() - def to_string(self, line_length: Optional[int] = None) -> str: if line_length is None: line_length = _get_default_length() @@ -237,7 +241,7 @@ def to_string(self, line_length: Optional[int] = None) -> str: ) for item in self.content: - if isinstance(item, (Block, Table)): + if isinstance(item, ProOutputFormatter): item_str = item.to_string(line_length=line_length) else: item_str = "\n".join(wrap_text(str(item), line_length)) + "\n"