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
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -40,7 +40,6 @@ EXTENSION_MAP: dict[str, str] = {
|
||||
".swift": "swift",
|
||||
".kt": "kotlin",
|
||||
".r": "r",
|
||||
".R": "r",
|
||||
".lua": "lua",
|
||||
".dockerfile": "docker",
|
||||
".ini": "ini",
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user