Cleo allows you to create beautiful and testable command-line interfaces.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
The styling and formatting system provides rich text output capabilities including colors, text formatting options, and custom styles. It enables creating visually appealing CLI output with consistent styling and theming support.
The main formatting engine that processes styled text with embedded tags and applies formatting.
class Formatter:
def __init__(self, decorated: bool = False, styles: dict[str, Style] | None = None) -> None:
"""
Create a text formatter.
Args:
decorated (bool): Whether to enable color/formatting output
styles (dict[str, Style] | None): Predefined styles dictionary
"""
def format(self, message: str) -> str:
"""
Format a message with embedded style tags.
Args:
message (str): Message with style tags like <info>text</info>
Returns:
str: Formatted message with ANSI codes or plain text
"""
def set_style(self, name: str, style: Style) -> None:
"""
Register a named style.
Args:
name (str): Style name for tag usage
style (Style): Style configuration
"""
def has_style(self, name: str) -> bool:
"""
Check if a style is registered.
Args:
name (str): Style name to check
Returns:
bool: True if style exists
"""
def get_style(self, name: str) -> Style:
"""
Get a registered style by name.
Args:
name (str): Style name
Returns:
Style: The style configuration
"""
def is_decorated(self) -> bool:
"""
Check if formatter produces decorated output.
Returns:
bool: True if decoration is enabled
"""
def decorated(self, decorated: bool = True) -> None:
"""
Enable or disable output decoration.
Args:
decorated (bool): Whether to enable decoration
"""Individual style configuration for text formatting including colors and text effects.
class Style:
def __init__(self, foreground: str | None = None, background: str | None = None,
options: list[str] | None = None) -> None:
"""
Create a text style.
Args:
foreground (str | None): Foreground color name
background (str | None): Background color name
options (list[str] | None): Formatting options (bold, italic, etc.)
"""
def foreground(self, foreground: str) -> Style:
"""
Set foreground color and return new style.
Args:
foreground (str): Color name
Returns:
Style: New style with foreground color
"""
def background(self, background: str) -> Style:
"""
Set background color and return new style.
Args:
background (str): Color name
Returns:
Style: New style with background color
"""
def bold(self, bold: bool = True) -> Style:
"""
Set bold formatting and return new style.
Args:
bold (bool): Whether to enable bold
Returns:
Style: New style with bold formatting
"""
def italic(self, italic: bool = True) -> Style:
"""
Set italic formatting and return new style.
Args:
italic (bool): Whether to enable italic
Returns:
Style: New style with italic formatting
"""
def underline(self, underline: bool = True) -> Style:
"""
Set underline formatting and return new style.
Args:
underline (bool): Whether to enable underline
Returns:
Style: New style with underline formatting
"""
def blink(self, blink: bool = True) -> Style:
"""
Set blink formatting and return new style.
Args:
blink (bool): Whether to enable blink
Returns:
Style: New style with blink formatting
"""
def reverse(self, reverse: bool = True) -> Style:
"""
Set reverse formatting and return new style.
Args:
reverse (bool): Whether to enable reverse
Returns:
Style: New style with reverse formatting
"""
def conceal(self, conceal: bool = True) -> Style:
"""
Set conceal formatting and return new style.
Args:
conceal (bool): Whether to enable conceal
Returns:
Style: New style with conceal formatting
"""
def apply(self, text: str) -> str:
"""
Apply this style to text.
Args:
text (str): Text to style
Returns:
str: Styled text with ANSI codes
"""Low-level color and formatting code generation for terminal output.
class Color:
COLORS: ClassVar[dict[str, tuple[int, int]]] = {
'black': (30, 40),
'red': (31, 41),
'green': (32, 42),
'yellow': (33, 43),
'blue': (34, 44),
'magenta': (35, 45),
'cyan': (36, 46),
'white': (37, 47),
'default': (39, 49)
}
AVAILABLE_OPTIONS: ClassVar[dict[str, dict[str, int]]] = {
'bold': {'set': 1, 'unset': 22},
'underscore': {'set': 4, 'unset': 24},
'blink': {'set': 5, 'unset': 25},
'reverse': {'set': 7, 'unset': 27},
'conceal': {'set': 8, 'unset': 28}
}
def __init__(self, foreground: str = "", background: str = "",
options: list[str] | None = None) -> None:
"""
Create a color configuration.
Args:
foreground (str): Foreground color name
background (str): Background color name
options (list[str] | None): Formatting options
"""
def apply(self, text: str) -> str:
"""
Apply color and formatting to text.
Args:
text (str): Text to colorize
Returns:
str: Text with ANSI escape codes
"""
def set(self) -> str:
"""
Get ANSI codes to enable this color/formatting.
Returns:
str: ANSI escape sequence to set formatting
"""
def unset(self) -> str:
"""
Get ANSI codes to disable this color/formatting.
Returns:
str: ANSI escape sequence to unset formatting
"""Cleo includes several predefined styles for common use cases:
# Predefined styles available in formatters
PREDEFINED_STYLES = {
'error': Style('red'), # Red text for errors
'info': Style('blue'), # Blue text for information
'comment': Style('green'), # Green text for comments
'question': Style('cyan'), # Cyan text for questions
'warning': Style('yellow'), # Yellow text for warnings
}from cleo.formatters.formatter import Formatter
from cleo.formatters.style import Style
# Create formatter
formatter = Formatter(decorated=True)
# Use predefined styles with tags
message = formatter.format("<info>Processing complete</info>")
error = formatter.format("<error>File not found</error>")
comment = formatter.format("<comment>This is a comment</comment>")
# Inline color specifications
colored = formatter.format("<fg=red>Red text</fg>")
background = formatter.format("<bg=yellow>Yellow background</>")
combined = formatter.format("<fg=white;bg=blue;options=bold>Bold white on blue</>")# Create custom styles
success_style = Style('green').bold()
warning_style = Style('yellow').background('black')
debug_style = Style('cyan').italic()
# Register custom styles
formatter.set_style('success', success_style)
formatter.set_style('warning', warning_style)
formatter.set_style('debug', debug_style)
# Use custom styles
output = formatter.format("<success>Operation successful!</success>")
warning = formatter.format("<warning>Deprecated feature used</warning>")
debug = formatter.format("<debug>Debug information here</debug>")# Chain style methods for complex formatting
fancy_style = (Style()
.foreground('white')
.background('blue')
.bold()
.underline())
# Apply style directly to text
styled_text = fancy_style.apply("Important Message")
# Use with formatter
formatter.set_style('fancy', fancy_style)
message = formatter.format("<fancy>This is fancy text</fancy>")# In a command class
class DeployCommand(Command):
def handle(self):
# Success messages
self.line("<info>Starting deployment...</info>")
# Warnings
self.line("<comment>Warning: This will overwrite existing files</comment>")
# Errors
self.line("<error>Deployment failed: Connection timeout</error>")
# Custom inline styling
self.line("<fg=green;options=bold>✓ All tests passed</>")
self.line("<bg=red;fg=white> ERROR </> Critical failure occurred")
# Add custom style for this command
self.add_style('highlight', fg='yellow', bg='black', options=['bold'])
self.line("<highlight>Key information highlighted</highlight>")class StatusCommand(Command):
def handle(self):
status = self.get_system_status()
# Style based on status
if status == 'healthy':
self.line("<info>System Status: Healthy</info>")
elif status == 'warning':
self.line("<comment>System Status: Warning</comment>")
else:
self.line("<error>System Status: Critical</error>")
# Progress indicators with styling
for i in range(5):
if i < 3:
self.line(f"<info>✓</info> Service {i+1}: Running")
else:
self.line(f"<error>✗</error> Service {i+1}: Stopped")class ReportCommand(Command):
def handle(self):
# Styled table headers and data
table = self.table()
table.set_headers([
'<info>Service</info>',
'<comment>Status</comment>',
'<question>Uptime</question>'
])
table.add_rows([
['Web Server', '<info>Running</info>', '5 days'],
['Database', '<error>Stopped</error>', '0 minutes'],
['Cache', '<comment>Warning</comment>', '2 hours']
])
table.render()
# Styled lists
self.line("\n<info>Available Commands:</info>")
commands = ['start', 'stop', 'restart', 'status']
for cmd in commands:
self.line(f" <comment>•</comment> {cmd}")def create_environment_formatter(env: str) -> Formatter:
"""Create formatter with environment-specific styles."""
formatter = Formatter(decorated=True)
if env == 'development':
formatter.set_style('env', Style('green').bold())
elif env == 'staging':
formatter.set_style('env', Style('yellow').bold())
elif env == 'production':
formatter.set_style('env', Style('red').bold())
return formatter
# Usage
formatter = create_environment_formatter('production')
message = formatter.format(f"<env>PRODUCTION</env> deployment initiated")Install with Tessl CLI
npx tessl i tessl/pypi-cleo