|
| 1 | +"""Utilities for handling and formatting application errors.""" |
| 2 | + |
| 3 | +from pydantic import BaseModel, ValidationError |
| 4 | +from rich.console import Console |
| 5 | +from rich.text import Text |
| 6 | + |
| 7 | + |
| 8 | +def format_pydantic_error( |
| 9 | + error: ValidationError, |
| 10 | + model_class: type[BaseModel], |
| 11 | + config_file: str, |
| 12 | + verbose: int = 0 |
| 13 | +) -> None: |
| 14 | + """Centralized formatter for Pydantic ValidationErrors using Rich. |
| 15 | +
|
| 16 | + :param error: The caught ValidationError object. |
| 17 | + :param model_class: The Pydantic model class that failed validation. |
| 18 | + :param config_file: The name/path of the config file being processed. |
| 19 | + :param verbose: Verbosity level to control error detail. |
| 20 | + """ |
| 21 | + console = Console(stderr=True) |
| 22 | + errors = error.errors() |
| 23 | + error_count = len(errors) |
| 24 | + |
| 25 | + # Header |
| 26 | + header = Text.assemble( |
| 27 | + (f"{error_count} Validation error{'s' if error_count > 1 else ''} ", "bold red"), |
| 28 | + ("in config file ", "white"), |
| 29 | + (f"'{config_file}'", "bold cyan"), |
| 30 | + (":", "white") |
| 31 | + ) |
| 32 | + console.print(header) |
| 33 | + console.print() |
| 34 | + |
| 35 | + # Smart Truncation: Show only first 5 unless verbose |
| 36 | + max_display = 5 if verbose < 2 else error_count |
| 37 | + display_errors = errors[:max_display] |
| 38 | + |
| 39 | + for i, err in enumerate(display_errors, 1): |
| 40 | + # 1. Resolve Location and Field Info |
| 41 | + loc_path = ".".join(str(v) for v in err["loc"]) |
| 42 | + err_type = err["type"] |
| 43 | + msg = err["msg"] |
| 44 | + |
| 45 | + # 2. Extract Field Metadata from the Model Class |
| 46 | + field_info = None |
| 47 | + current_model = model_class |
| 48 | + |
| 49 | + for part in err["loc"]: |
| 50 | + # Check if current_model is a Pydantic class and contains the field |
| 51 | + if (isinstance(current_model, type) and |
| 52 | + issubclass(current_model, BaseModel) and |
| 53 | + part in current_model.model_fields): |
| 54 | + |
| 55 | + field_info = current_model.model_fields[part] |
| 56 | + |
| 57 | + # Move deeper into the tree if the annotation is another model |
| 58 | + annotation = field_info.annotation |
| 59 | + if (isinstance(annotation, type) and |
| 60 | + issubclass(annotation, BaseModel)): |
| 61 | + current_model = annotation |
| 62 | + else: |
| 63 | + # We have reached a leaf node or a complex type (List, etc.) |
| 64 | + # Stop traversing but keep the field_info |
| 65 | + current_model = None |
| 66 | + else: |
| 67 | + field_info = None |
| 68 | + break |
| 69 | + |
| 70 | + # 3. Build the Display |
| 71 | + error_panel = Text() |
| 72 | + error_panel.append(f"({i}) In '", style="white") |
| 73 | + error_panel.append(loc_path, style="bold yellow") |
| 74 | + error_panel.append("':\n", style="white") |
| 75 | + |
| 76 | + # Error detail |
| 77 | + error_panel.append(f" {msg}\n", style="red") |
| 78 | + |
| 79 | + # Helpful context from Field metadata |
| 80 | + if field_info: |
| 81 | + if field_info.title: |
| 82 | + error_panel.append(" Expected: ", style="dim") |
| 83 | + error_panel.append(f"{field_info.title}\n", style="italic green") |
| 84 | + if verbose > 0 and field_info.description: |
| 85 | + error_panel.append(" Description: ", style="dim") |
| 86 | + error_panel.append(f"{field_info.description}\n", style="dim italic") |
| 87 | + |
| 88 | + # Documentation Link |
| 89 | + error_panel.append(" See: ", style="dim") |
| 90 | + error_panel.append( |
| 91 | + f"https://opensuse.github.io/docbuild/latest/errors/{err_type}.html", |
| 92 | + style="link underline blue" |
| 93 | + ) |
| 94 | + |
| 95 | + console.print(error_panel) |
| 96 | + console.print() |
| 97 | + |
| 98 | + # Footer for Truncation |
| 99 | + if error_count > max_display: |
| 100 | + console.print( |
| 101 | + f"[dim]... and {error_count - max_display} more errors. " |
| 102 | + "Use '-vv' to see all errors.[/dim]\n" |
| 103 | + ) |
0 commit comments