From 5db15a8a17d43faed85a1ebd224f7cfd786209e7 Mon Sep 17 00:00:00 2001 From: Yunxiao Xu Date: Wed, 1 Apr 2026 16:02:56 -0700 Subject: [PATCH] Fix review issues: error handling, stdin TTY hint, narrow exceptions - Handle UnicodeDecodeError and PermissionError for file reading - Show hint when stdin is a TTY and no file given - Narrow JSON fallback exception from Exception to (SyntaxError, ValueError) - Rename 'type' parameter to 'file_type' to avoid shadowing builtin - Remove dead '.R' entry from EXTENSION_MAP --- src/rp/cli.py | 15 ++++++++++++--- src/rp/detect.py | 1 - src/rp/render.py | 2 +- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/rp/cli.py b/src/rp/cli.py index 440c2a0..318dfe1 100644 --- a/src/rp/cli.py +++ b/src/rp/cli.py @@ -50,7 +50,7 @@ def main( Optional[Path], typer.Argument(help="File to rich-print. Use '-' or omit to read from stdin."), ] = None, - type: Annotated[ + file_type: Annotated[ Optional[str], typer.Option( "--type", "-t", help="Force file type (e.g. json, python, markdown)." @@ -89,6 +89,8 @@ def main( console = Console() if file is None or str(file) == "-": + if sys.stdin.isatty(): + console.print("[dim]Reading from stdin. Press Ctrl+D to end.[/dim]") content = sys.stdin.read() file_path = None else: @@ -98,14 +100,21 @@ def main( if file.is_dir(): console.print(f"[red]Error:[/red] Is a directory: {file}") raise typer.Exit(code=1) - content = file.read_text(encoding="utf-8") + try: + content = file.read_text(encoding="utf-8") + except UnicodeDecodeError: + console.print(f"[red]Error:[/red] Cannot read binary file: {file}") + raise typer.Exit(code=1) + except (PermissionError, OSError) as e: + console.print(f"[red]Error:[/red] {e}") + raise typer.Exit(code=1) file_path = str(file) if not content: console.print("[dim]Empty input, nothing to display.[/dim]") raise typer.Exit() - file_type = detect_type(path=file_path, content=content, explicit_type=type) + file_type = detect_type(path=file_path, content=content, explicit_type=file_type) options = RenderOptions( theme=theme, diff --git a/src/rp/detect.py b/src/rp/detect.py index d199b5d..19c2f50 100644 --- a/src/rp/detect.py +++ b/src/rp/detect.py @@ -40,7 +40,6 @@ EXTENSION_MAP: dict[str, str] = { ".swift": "swift", ".kt": "kotlin", ".r": "r", - ".R": "r", ".lua": "lua", ".dockerfile": "docker", ".ini": "ini", diff --git a/src/rp/render.py b/src/rp/render.py index 158e925..d4ae8f3 100644 --- a/src/rp/render.py +++ b/src/rp/render.py @@ -39,7 +39,7 @@ def render( elif file_type in _JSON_TYPES: try: renderable = RichJSON(content) - except Exception: + except (SyntaxError, ValueError): renderable = Syntax( content, "json", theme=options.theme, line_numbers=line_numbers )