Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Remove no_color
  • Loading branch information
jiasli committed Dec 24, 2020
commit fa9985e7f18f5624cd21484404c313368a1909bd
3 changes: 2 additions & 1 deletion src/azure-cli-core/azure/cli/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ def __init__(self, **kwargs):

self.progress_controller = None

format_styled_text.enable_color = self.enable_color
if not self.enable_color:
format_styled_text.theme = 'none'

def refresh_request_id(self):
"""Assign a new random GUID as x-ms-client-request-id
Expand Down
70 changes: 37 additions & 33 deletions src/azure-cli-core/azure/cli/core/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ class Style(str, Enum):
WARNING = "warning"


# Theme that doesn't contain any style
THEME_NONE = {}

# Theme to be used on a dark-themed terminal
THEME_DARK = {
# Style to ANSI escape sequence mapping
Expand Down Expand Up @@ -71,38 +74,40 @@ def print_styled_text(*styled_text_objects, file=None, **kwargs):
"""
Print styled text.

:param styled_text_objects: The input text objects. Each object can be in these formats:
- text
- (style, text)
- [(style, text), ...]
:param styled_text_objects: The input text objects. See format_styled_text for formats of each object.
:param file: The file to print the styled text. The default target is sys.stderr.
"""
formatted_list = [format_styled_text(obj) for obj in styled_text_objects]
# Always fetch the latest sys.stderr in case it has been wrapped by colorama.
print(*formatted_list, file=file or sys.stderr, **kwargs)


def format_styled_text(styled_text, theme=None, enable_color=None):
"""Format styled text.
Color is turned on by default. To turn off color for all invocations of this function, set
`format_styled_text.enable_color = False`. To turn off color only for one invocation, set parameter
`enable_color=False`.
def format_styled_text(styled_text, theme=None):
"""Format styled text. Dark theme used by default. Available themes are 'dark', 'light', 'none'.

To change theme for all invocations of this function, set `format_styled_text.theme`.
To change theme for one invocation, set parameter `theme`.

:param styled_text: See print_styled_text for detail.
:param theme: The theme used to format text. Cant be 'light', 'dark' or the theme dict.
:param enable_color: Whether color should be enabled. If not provided, the function attribute `enable_color`
will be honored.
:param styled_text: Can be in these formats:
- text
- (style, text)
- [(style, text), ...]
:param theme: The theme used to format text. Can be theme name or dict.
"""
if enable_color is None:
enable_color = getattr(format_styled_text, "enable_color", True)
if theme is None:
theme = getattr(format_styled_text, "theme", THEME_DARK)

# Convert str to the theme dict
if theme == 'dark':
theme = THEME_DARK
if theme == 'light':
theme = THEME_LIGHT
if isinstance(theme, str):
if theme.lower() == 'none':
theme = THEME_NONE
elif theme.lower() == 'dark':
theme = THEME_DARK
elif theme.lower() == 'light':
theme = THEME_LIGHT
else:
from azure.cli.core.azclierror import CLIInternalError
raise CLIInternalError("Invalid theme. Supported themes: none, dark, light")

# Cache the value of is_legacy_powershell
if not hasattr(format_styled_text, "_is_legacy_powershell"):
Expand All @@ -128,24 +133,23 @@ def format_styled_text(styled_text, theme=None, enable_color=None):
from azure.cli.core.azclierror import CLIInternalError
raise CLIInternalError("Invalid styled text. It should be a list of 2-element tuples.")

style = text[0]
# Check if the specified style is defined
if style not in theme:
from azure.cli.core.azclierror import CLIInternalError
raise CLIInternalError("Invalid style. Only use pre-defined style in Style enum.")

escape_seq = theme[text[0]]
# Replace blue in powershell.exe
if is_legacy_powershell and escape_seq in POWERSHELL_COLOR_REPLACEMENT:
escape_seq = POWERSHELL_COLOR_REPLACEMENT[escape_seq]
style, raw_text = text

if enable_color:
formatted_parts.append(escape_seq + text[1])
if theme is THEME_NONE:
formatted_parts.append(raw_text)
else:
formatted_parts.append(text[1])
try:
escape_seq = theme[style]
except KeyError:
from azure.cli.core.azclierror import CLIInternalError
raise CLIInternalError("Invalid style. Only use pre-defined style in Style enum.")
# Replace blue in powershell.exe
if is_legacy_powershell and escape_seq in POWERSHELL_COLOR_REPLACEMENT:
escape_seq = POWERSHELL_COLOR_REPLACEMENT[escape_seq]
formatted_parts.append(escape_seq + raw_text)

# Reset control sequence
if enable_color:
if theme is not THEME_NONE:
formatted_parts.append(Fore.RESET)
return ''.join(formatted_parts)

Expand Down
12 changes: 6 additions & 6 deletions src/azure-cli-core/azure/cli/core/tests/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def test_format_styled_text_on_error(self):
with self.assertRaisesRegex(CLIInternalError, "Invalid styled text."):
format_styled_text(["dummy text"])

def test_format_styled_text_enable_color(self):
def test_format_styled_text_theme(self):
from azure.cli.core.style import Style, format_styled_text
styled_text = [
(Style.PRIMARY, "White: Primary text color\n"),
Expand All @@ -74,22 +74,22 @@ def test_format_styled_text_enable_color(self):
self.assertEqual(formatted, excepted)

# Color is turned off via param
formatted = format_styled_text(styled_text, enable_color=False)
formatted = format_styled_text(styled_text, theme='none')
excepted_plaintext = ("White: Primary text color\n"
"Bright Black: Secondary text color\n")
self.assertEqual(formatted, excepted_plaintext)

# Color is turned off via function attribute
format_styled_text.enable_color = False
format_styled_text.theme = 'none'
formatted = format_styled_text(styled_text)
self.assertEqual(formatted, excepted_plaintext)

# Function attribute is overridden by param
format_styled_text.enable_color = True
formatted = format_styled_text(styled_text, enable_color=False)
format_styled_text.theme = 'dark'
formatted = format_styled_text(styled_text, theme='none')
self.assertEqual(formatted, excepted_plaintext)

delattr(format_styled_text, "enable_color")
delattr(format_styled_text, "theme")

@mock.patch("builtins.print")
@mock.patch("azure.cli.core.style.format_styled_text")
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli/azure/cli/command_modules/util/_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,4 @@ def load_arguments(self, _):

with self.argument_context('demo style') as c:
c.argument('no_color', arg_type=get_three_state_flag(), help='Disable color.', default=False)
c.argument('theme', arg_type=get_enum_type(['dark', 'light']), help='The theme to format styled text.', default='dark')
c.argument('theme', arg_type=get_enum_type(['none', 'dark', 'light']), help='The theme to format styled text.', default='dark')
3 changes: 1 addition & 2 deletions src/azure-cli/azure/cli/command_modules/util/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,8 @@ def upgrade_version(cmd, update_all=None, yes=None): # pylint: disable=too-many
else auto_upgrade_msg)


def demo_style(cmd, no_color=None, theme=None): # pylint: disable=unused-argument
def demo_style(cmd, theme=None): # pylint: disable=unused-argument
from azure.cli.core.style import Style, print_styled_text, format_styled_text
format_styled_text.enable_color = not no_color
format_styled_text.theme = theme
print_styled_text("[How to call print_styled_text]")
# Print an empty line
Expand Down