Skip to content

Commit

Permalink
cli: add colorize method for the new CLI
Browse files Browse the repository at this point in the history
This method should be the standard way of colorizing any user facing
string in the pro client, in the future.

Signed-off-by: Renan Rodrigo <[email protected]>
  • Loading branch information
renanrodrigo committed Sep 12, 2024
1 parent 78fed31 commit 5617d30
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
23 changes: 23 additions & 0 deletions uaclient/cli/formatter.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
import os
import re
import sys
from enum import Enum

from uaclient.config import UAConfig


class TxtColor(Enum):
BLUE = "\033[94m"
BOLD = "\033[1m"
GREEN = "\033[92m"
GREY = "\033[37m"
ORANGE = "\033[38;5;208m"
RED = "\033[91m"
YELLOW = "\033[93m"
ENDC = "\033[0m"


# Class attributes and methods so we don't need singletons or globals for this
class ProOutputFormatterConfig:
use_utf8 = True
Expand Down Expand Up @@ -57,3 +69,14 @@ def decolorize(self):
def split(self, sep=None, maxsplit=-1):
splitted = super().split(sep=sep, maxsplit=maxsplit)
return [self.__class__(s) for s in splitted]


def colorize(input_string: str, color: TxtColor) -> str:
if not ProOutputFormatterConfig.use_color:
return input_string

return_string = ProColorString(color.value + input_string)
if not return_string.endswith(TxtColor.ENDC.value):
return_string += TxtColor.ENDC.value

return return_string
19 changes: 19 additions & 0 deletions uaclient/cli/tests/test_cli_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from uaclient.cli.formatter import ProColorString
from uaclient.cli.formatter import ProOutputFormatterConfig as POFC
from uaclient.cli.formatter import TxtColor, colorize

M_PATH = "uaclient.cli.formatter."

Expand Down Expand Up @@ -155,3 +156,21 @@ def test_split_produces_color_strings(self):
] == splitted
for chunk in splitted:
assert isinstance(chunk, ProColorString)


class TestColorize:
def test_adds_color_to_strings(self, FakeConfig):
POFC.use_color = True
assert "\033[94mtest_string\033[0m" == colorize(
"test_string", TxtColor.BLUE
)

def test_noop_if_no_color_set(self, FakeConfig):
POFC.use_color = False
assert "test_string" == colorize("test_string", TxtColor.BLUE)

def does_not_add_multiple_end_characters(self, FakeConfig):
POFC.use_color = True
blue_string = colorize("test_string", TxtColor.BLUE)
bold_blue_string = colorize(blue_string, TxtColor.BOLD)
assert "\033[1m\033[94mtest_string\033[0m" == bold_blue_string

0 comments on commit 5617d30

Please sign in to comment.