-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathformatting.py
More file actions
101 lines (79 loc) · 2.85 KB
/
formatting.py
File metadata and controls
101 lines (79 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"""Output formatting — Rich Markdown rendering and JSON display."""
from __future__ import annotations
import json
import sys
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.text import Text
from rich.theme import Theme
# ── Custom theme for Talk Python branding ────────────────────────────────────
_TALK_PYTHON_THEME = Theme(
{
'tp.title': 'bold cyan',
'tp.heading': 'bold magenta',
'tp.id': 'bold yellow',
'tp.url': 'blue underline',
'tp.date': 'green',
'tp.dim': 'dim',
'tp.error': 'bold red',
'tp.success': 'bold green',
'tp.label': 'bold white',
}
)
console = Console(theme=_TALK_PYTHON_THEME, highlight=False)
error_console = Console(theme=_TALK_PYTHON_THEME, stderr=True, highlight=False)
def is_tty() -> bool:
"""Return True if stdout is connected to a terminal."""
return sys.stdout.isatty()
def display(content: str, output_format: str) -> None:
"""Route content to the appropriate renderer."""
if output_format == 'json':
display_json(content)
elif output_format == 'markdown':
display_markdown_raw(content)
else:
display_markdown(content)
def display_markdown_raw(content: str) -> None:
"""Print raw Markdown content to stdout without any Rich formatting."""
print(content)
def display_markdown(content: str) -> None:
"""Render Markdown content with Rich, wrapped in a styled panel."""
md = Markdown(content, code_theme='monokai')
panel = Panel(
md,
border_style='cyan',
title='[bold cyan]Talk Python[/bold cyan]',
title_align='left',
padding=(1, 2),
)
console.print(panel)
def display_json(content: str) -> None:
"""Output JSON content — pretty-printed if on a TTY, raw otherwise."""
try:
data = json.loads(content)
except (json.JSONDecodeError, TypeError):
# Server may have returned Markdown even though JSON was requested;
# fall back to printing the raw text.
console.print(content)
return
if is_tty():
from rich.syntax import Syntax
formatted = json.dumps(data, indent=2, ensure_ascii=False)
syntax = Syntax(formatted, 'json', theme='monokai', word_wrap=True)
console.print(syntax)
else:
# Raw compact JSON for piping
print(json.dumps(data, ensure_ascii=False))
def print_error(message: str) -> None:
"""Print a styled error message to stderr."""
error_console.print(
Text.assemble(
('ERROR', 'bold red'),
(' ', ''),
(message, 'red'),
)
)
def print_info(message: str) -> None:
"""Print a styled informational message."""
console.print(f'[tp.dim]{message}[/tp.dim]')