Developer tools dump stack traces, exit codes, and jargon. Figuring out *what to do next* often means searching the same Stack Overflow answers again.
| 1 | """Stdin and file input helpers.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import sys |
| 6 | from pathlib import Path |
| 7 | |
| 8 | |
| 9 | class InputError(Exception): |
| 10 | """Raised when input cannot be obtained or read.""" |
| 11 | |
| 12 | |
| 13 | def stdin_is_piped() -> bool: |
| 14 | """Return True when stdin is not an interactive terminal.""" |
| 15 | try: |
| 16 | return not sys.stdin.isatty() |
| 17 | except (OSError, ValueError): |
| 18 | return False |
| 19 | |
| 20 | |
| 21 | def read_stdin(*, force: bool = False) -> str: |
| 22 | """Read all of stdin. |
| 23 | |
| 24 | When ``force`` is False, only reads if stdin is piped. |
| 25 | """ |
| 26 | if not force and not stdin_is_piped(): |
| 27 | raise InputError( |
| 28 | "No input provided. Pass error text as arguments, use --file, " |
| 29 | "--stdin, or pipe output into why-failed." |
| 30 | ) |
| 31 | try: |
| 32 | return sys.stdin.read() |
| 33 | except OSError as exc: |
| 34 | raise InputError(f"Failed to read stdin: {exc}") from exc |
| 35 | |
| 36 | |
| 37 | def read_file(path: str | Path) -> str: |
| 38 | """Read an explicitly supplied file path (UTF-8 with replacement).""" |
| 39 | file_path = Path(path) |
| 40 | if not file_path.is_file(): |
| 41 | raise InputError(f"File not found: {file_path}") |
| 42 | try: |
| 43 | return file_path.read_text(encoding="utf-8", errors="replace") |
| 44 | except OSError as exc: |
| 45 | raise InputError(f"Failed to read file {file_path}: {exc}") from exc |
| 46 | |
| 47 | |
| 48 | def join_args(args: list[str]) -> str: |
| 49 | """Join CLI text arguments into a single error string.""" |
| 50 | return " ".join(args) |