|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import Any, Callable |
| 4 | + |
| 5 | +from griffe import ( |
| 6 | + Attribute, |
| 7 | + Class, |
| 8 | + Docstring, |
| 9 | + Function, |
| 10 | + Kind, |
| 11 | + get_logger, |
| 12 | +) |
| 13 | +from pydantic.fields import FieldInfo |
| 14 | + |
| 15 | +from griffe_pydantic._internal import common |
| 16 | + |
| 17 | +_logger = get_logger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +def _process_attribute(obj: Any, attr: Attribute, cls: Class, *, processed: set[str]) -> None: |
| 21 | + """Handle Pydantic fields.""" |
| 22 | + if attr.canonical_path in processed: |
| 23 | + return |
| 24 | + processed.add(attr.canonical_path) |
| 25 | + if attr.name == "model_config": |
| 26 | + cls.extra[common._self_namespace]["config"] = obj |
| 27 | + return |
| 28 | + |
| 29 | + if not isinstance(obj, FieldInfo): |
| 30 | + return |
| 31 | + |
| 32 | + attr.labels = {"pydantic-field"} |
| 33 | + attr.value = obj.default |
| 34 | + constraints = {} |
| 35 | + for constraint in common._field_constraints: |
| 36 | + if (value := getattr(obj, constraint, None)) is not None: |
| 37 | + constraints[constraint] = value |
| 38 | + attr.extra[common._self_namespace]["constraints"] = constraints |
| 39 | + |
| 40 | + # Populate docstring from the field's `description` argument. |
| 41 | + if not attr.docstring and (docstring := obj.description): |
| 42 | + attr.docstring = Docstring(docstring, parent=attr) |
| 43 | + |
| 44 | + |
| 45 | +def _process_function(obj: Callable, func: Function, cls: Class, *, processed: set[str]) -> None: |
| 46 | + """Handle Pydantic field validators.""" |
| 47 | + if func.canonical_path in processed: |
| 48 | + return |
| 49 | + processed.add(func.canonical_path) |
| 50 | + if dec_info := getattr(obj, "decorator_info", None): |
| 51 | + common._process_function(func, cls, dec_info.fields) |
| 52 | + |
| 53 | + |
| 54 | +def _process_class(obj: type, cls: Class, *, processed: set[str], schema: bool = False) -> None: |
| 55 | + """Detect and prepare Pydantic models.""" |
| 56 | + common._process_class(cls) |
| 57 | + if schema: |
| 58 | + cls.extra[common._self_namespace]["schema"] = common._json_schema(obj) |
| 59 | + for member in cls.all_members.values(): |
| 60 | + kind = member.kind |
| 61 | + if kind is Kind.ATTRIBUTE: |
| 62 | + _process_attribute(getattr(obj, member.name), member, cls, processed=processed) # type: ignore[arg-type] |
| 63 | + elif kind is Kind.FUNCTION: |
| 64 | + _process_function(getattr(obj, member.name), member, cls, processed=processed) # type: ignore[arg-type] |
0 commit comments