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 | """Terminal and JSON output formatting.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import contextlib |
| 6 | import json |
| 7 | import sys |
| 8 | from typing import Any |
| 9 | |
| 10 | from rich.console import Console |
| 11 | from rich.text import Text |
| 12 | |
| 13 | from why_failed.models import AnalysisResult, ErrorMatch |
| 14 | |
| 15 | # Prefer the spec's marks; console uses UTF-8 with replacement when available. |
| 16 | _FAIL_MARK = "\u2717" |
| 17 | _ARROW = "\u2192" |
| 18 | _UNKNOWN_MARK = "?" |
| 19 | |
| 20 | |
| 21 | def _prepare_stream() -> None: |
| 22 | for stream in (sys.stdout, sys.stderr): |
| 23 | if hasattr(stream, "reconfigure"): |
| 24 | with contextlib.suppress(OSError, ValueError, AttributeError): |
| 25 | stream.reconfigure(encoding="utf-8", errors="replace") |
| 26 | |
| 27 | |
| 28 | def get_console(*, stderr: bool = False) -> Console: |
| 29 | """Build a Console bound to the *current* stdout/stderr (CliRunner-safe).""" |
| 30 | _prepare_stream() |
| 31 | return Console( |
| 32 | file=sys.stderr if stderr else sys.stdout, |
| 33 | soft_wrap=True, |
| 34 | emoji=False, |
| 35 | legacy_windows=False, |
| 36 | highlight=False, |
| 37 | ) |
| 38 | |
| 39 | |
| 40 | def _confidence_label(value: str) -> str: |
| 41 | return value.capitalize() |
| 42 | |
| 43 | |
| 44 | def format_match_rich(match: ErrorMatch, result: AnalysisResult, *, verbose: bool = False) -> None: |
| 45 | """Print a successful match to the terminal.""" |
| 46 | console = get_console() |
| 47 | title = Text() |
| 48 | title.append(f"{_FAIL_MARK} ", style="bold red") |
| 49 | title.append(match.title, style="bold") |
| 50 | console.print(title) |
| 51 | console.print() |
| 52 | |
| 53 | console.print(Text("WHY", style="bold cyan")) |
| 54 | console.print(match.why) |
| 55 | console.print() |
| 56 | |
| 57 | if match.checks: |
| 58 | console.print(Text("CHECK", style="bold cyan")) |
| 59 | for check in match.checks: |
| 60 | console.print(f"{_ARROW} {check}") |
| 61 | console.print() |
| 62 | |
| 63 | if match.fixes: |
| 64 | console.print(Text("FIX", style="bold cyan")) |
| 65 | if len(match.fixes) == 1: |
| 66 | console.print(match.fixes[0]) |
| 67 | else: |
| 68 | for i, fix in enumerate(match.fixes, start=1): |
| 69 | console.print(f"{i}. {fix}") |
| 70 | console.print() |
| 71 | |
| 72 | console.print(f"Confidence: {_confidence_label(match.confidence)}") |
| 73 | |
| 74 | if verbose: |
| 75 | _print_verbose(console, result) |
| 76 | |
| 77 | |
| 78 | def format_no_match_rich(result: AnalysisResult, *, verbose: bool = False) -> None: |
| 79 | """Print the no-match message.""" |
| 80 | console = get_console() |
| 81 | console.print(Text(f"{_UNKNOWN_MARK} No matching rule found.", style="bold yellow")) |
| 82 | console.print() |
| 83 | console.print("The error was not recognized by the local rule database.") |
| 84 | console.print() |
| 85 | console.print("Try:") |
| 86 | console.print(f'{_ARROW} why-failed --verbose "..."') |
| 87 | console.print(f"{_ARROW} contribute a new rule") |
| 88 | if verbose: |
| 89 | console.print() |
| 90 | _print_verbose(console, result) |
| 91 | |
| 92 | |
| 93 | def format_quiet(match: ErrorMatch | None) -> None: |
| 94 | """Print only the primary fix (or nothing useful if no match).""" |
| 95 | if match is None or not match.fixes: |
| 96 | return |
| 97 | get_console().print(match.fixes[0]) |
| 98 | |
| 99 | |
| 100 | def _print_verbose(console: Console, result: AnalysisResult) -> None: |
| 101 | console.print() |
| 102 | console.print(Text("MATCH", style="bold dim")) |
| 103 | if result.match: |
| 104 | console.print(f"Rule: {result.match.rule_id}") |
| 105 | console.print(f"Score: {result.match.score}") |
| 106 | console.print(f"Confidence: {_confidence_label(result.match.confidence)}") |
| 107 | else: |
| 108 | console.print("Rule: (none)") |
| 109 | |
| 110 | if result.normalized_preview: |
| 111 | console.print() |
| 112 | console.print(Text("NORMALIZED", style="bold dim")) |
| 113 | console.print(result.normalized_preview) |
| 114 | |
| 115 | if result.truncated: |
| 116 | console.print("(input was truncated)") |
| 117 | |
| 118 | if result.alternatives: |
| 119 | console.print() |
| 120 | console.print(Text("ALTERNATIVES", style="bold dim")) |
| 121 | for alt in result.alternatives: |
| 122 | console.print(alt.rule.id) |
| 123 | console.print(f"Score: {alt.score}") |
| 124 | |
| 125 | |
| 126 | def to_json_dict(result: AnalysisResult) -> dict[str, Any]: |
| 127 | """Build a stable JSON-serializable dict.""" |
| 128 | if not result.matched or result.match is None: |
| 129 | return { |
| 130 | "matched": False, |
| 131 | "rule_id": None, |
| 132 | } |
| 133 | |
| 134 | m = result.match |
| 135 | return { |
| 136 | "matched": True, |
| 137 | "rule_id": m.rule_id, |
| 138 | "tool": m.tool, |
| 139 | "title": m.title, |
| 140 | "why": m.why, |
| 141 | "checks": m.checks, |
| 142 | "fixes": m.fixes, |
| 143 | "confidence": m.confidence, |
| 144 | } |
| 145 | |
| 146 | |
| 147 | def format_json(result: AnalysisResult) -> str: |
| 148 | """Return compact, script-friendly JSON.""" |
| 149 | return json.dumps(to_json_dict(result), indent=2, ensure_ascii=False) |
| 150 | |
| 151 | |
| 152 | def format_rules_list() -> None: |
| 153 | """Print available rules grouped by tool.""" |
| 154 | from why_failed.registry import get_all_rules, rules_by_tool |
| 155 | |
| 156 | console = get_console() |
| 157 | all_rules = get_all_rules() |
| 158 | console.print(f"Available rules: {len(all_rules)}") |
| 159 | console.print() |
| 160 | for tool, rules in rules_by_tool().items(): |
| 161 | console.print(tool) |
| 162 | for rule in rules: |
| 163 | console.print(f" {rule.id}") |
| 164 | console.print() |