Implement rp CLI: rich-print markdown, JSON, code, and more
- Add typer CLI with auto file-type detection by extension - Support markdown (rich.Markdown), JSON (rich.JSON), and 30+ code languages via Pygments syntax highlighting - Features: line numbers toggle, pager support, stdin input, configurable color themes - Project metadata: MIT license, author, classifiers, entry point
This commit is contained in:
55
src/rp/render.py
Normal file
55
src/rp/render.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""Core rendering module for rp."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from rich.console import Console
|
||||
from rich.json import JSON as RichJSON
|
||||
from rich.markdown import Markdown
|
||||
from rich.syntax import Syntax
|
||||
|
||||
|
||||
@dataclass
|
||||
class RenderOptions:
|
||||
theme: str = "monokai"
|
||||
line_numbers: bool | None = None
|
||||
pager: bool | None = None
|
||||
|
||||
|
||||
_MARKDOWN_TYPES = {"markdown", "md"}
|
||||
_JSON_TYPES = {"json"}
|
||||
|
||||
|
||||
def render(
|
||||
content: str, file_type: str, console: Console, options: RenderOptions
|
||||
) -> None:
|
||||
line_numbers = options.line_numbers
|
||||
if line_numbers is None:
|
||||
line_numbers = file_type not in _MARKDOWN_TYPES and file_type not in _JSON_TYPES
|
||||
|
||||
use_pager = options.pager
|
||||
if use_pager is None:
|
||||
import sys
|
||||
|
||||
use_pager = sys.stdout.isatty()
|
||||
|
||||
if file_type in _MARKDOWN_TYPES:
|
||||
renderable = Markdown(content)
|
||||
elif file_type in _JSON_TYPES:
|
||||
try:
|
||||
renderable = RichJSON(content)
|
||||
except Exception:
|
||||
renderable = Syntax(
|
||||
content, "json", theme=options.theme, line_numbers=line_numbers
|
||||
)
|
||||
else:
|
||||
renderable = Syntax(
|
||||
content, file_type, theme=options.theme, line_numbers=line_numbers
|
||||
)
|
||||
|
||||
if use_pager:
|
||||
with console.pager(styles=True):
|
||||
console.print(renderable)
|
||||
else:
|
||||
console.print(renderable)
|
||||
Reference in New Issue
Block a user