Skip to content

Commit

Permalink
cli: create superclass for output formatters
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
renanrodrigo committed Sep 24, 2024
1 parent c53ac05 commit b3870e7
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions uaclient/cli/formatter.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import abc
import os
import re
import sys
Expand Down Expand Up @@ -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__(
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -204,7 +211,7 @@ def _fill_row(self, row: List[str]) -> str:
return output


class Block:
class Block(ProOutputFormatter):
INDENT_SIZE = 4
INDENT_CHAR = " "

Expand All @@ -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()
Expand All @@ -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"
Expand Down

0 comments on commit b3870e7

Please sign in to comment.