| 1 |
"""Griffe extensions.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import ast |
| 6 |
from typing import TYPE_CHECKING, Any |
| 7 |
import textwrap |
| 8 |
|
| 9 |
from griffe import Docstring, Extension, DocstringSectionAdmonition, DocstringSectionText, Visitor, Inspector |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
from griffe import Class, Function, ObjectNode |
| 13 |
|
| 14 |
|
| 15 |
def _deprecated(obj: Class | Function) -> str | None: |
| 16 |
for decorator in obj.decorators: |
| 17 |
if decorator.callable_path == "markdown.util.deprecated": |
| 18 |
return ast.literal_eval(str(decorator.value.arguments[0])) |
| 19 |
return None |
| 20 |
|
| 21 |
|
| 22 |
class DeprecatedExtension(Extension): |
| 23 |
"""Griffe extension for `@markdown.util.deprecated` decorator support.""" |
| 24 |
|
| 25 |
def _insert_message(self, obj: Function | Class, message: str) -> None: |
| 26 |
if not obj.docstring: |
| 27 |
obj.docstring = Docstring("", parent=obj) |
| 28 |
sections = obj.docstring.parsed |
| 29 |
sections.insert(0, DocstringSectionAdmonition(kind="warning", text=message, title="Deprecated")) |
| 30 |
|
| 31 |
def on_class_instance(self, node: ast.AST | ObjectNode, cls: Class, agent: Visitor | Inspector, **kwargs: Any) -> None: # noqa: ARG002 |
| 32 |
"""Add section to docstrings of deprecated classes.""" |
| 33 |
if message := _deprecated(cls): |
| 34 |
self._insert_message(cls, message) |
| 35 |
cls.labels.add("deprecated") |
| 36 |
|
| 37 |
def on_function_instance(self, node: ast.AST | ObjectNode, func: Function, agent: Visitor | Inspector, **kwargs: Any) -> None: # noqa: ARG002 |
| 38 |
"""Add section to docstrings of deprecated functions.""" |
| 39 |
if message := _deprecated(func): |
| 40 |
self._insert_message(func, message) |
| 41 |
func.labels.add("deprecated") |
| 42 |
|
| 43 |
|
| 44 |
class PriorityTableExtension(Extension): |
| 45 |
""" Griffe extension to insert a table of processor priority in specified functions. """ |
| 46 |
|
| 47 |
def __init__(self, paths: list[str] | None = None) -> None: |
| 48 |
super().__init__() |
| 49 |
self.paths = paths |
| 50 |
|
| 51 |
def linked_obj(self, value: str, path: str) -> str: |
| 52 |
""" Wrap object name in reference link. """ |
| 53 |
return f'[`{value}`][{path}.{value}]' |
| 54 |
|
| 55 |
def on_function_instance(self, node: ast.AST | ObjectNode, func: Function, agent: Visitor | Inspector, **kwargs: Any) -> None: # noqa: ARG002 |
| 56 |
"""Add table to specified function docstrings.""" |
| 57 |
if self.paths and func.path not in self.paths: |
| 58 |
return # skip objects that were not selected |
| 59 |
|
| 60 |
# Table header |
| 61 |
data = [ |
| 62 |
'Class Instance | Name | Priority', |
| 63 |
'-------------- | ---- | :------:' |
| 64 |
] |
| 65 |
|
| 66 |
# Extract table body from source code of function. |
| 67 |
for obj in node.body: |
| 68 |
# Extract the arguments passed to `util.Registry.register`. |
| 69 |
if isinstance(obj, ast.Expr) and isinstance(obj.value, ast.Call) and obj.value.func.attr == 'register': |
| 70 |
_args = obj.value.args |
| 71 |
cls = self.linked_obj(_args[0].func.id, func.path.rsplit('.', 1)[0]) |
| 72 |
name = _args[1].value |
| 73 |
priority = str(_args[2].value) |
| 74 |
if func.name == ('build_inlinepatterns'): |
| 75 |
# Include Pattern: first arg passed to class |
| 76 |
if isinstance(_args[0].args[0], ast.Constant): |
| 77 |
# Pattern is a string |
| 78 |
value = f'`"{_args[0].args[0].value}"`' |
| 79 |
else: |
| 80 |
# Pattern is a variable |
| 81 |
value = self.linked_obj(_args[0].args[0].id, func.path.rsplit('.', 1)[0]) |
| 82 |
cls = f'{cls}({value})' |
| 83 |
data.append(f'{cls} | `{name}` | `{priority}`') |
| 84 |
|
| 85 |
table = '\n'.join(data) |
| 86 |
body = ( |
| 87 |
f"Return a [`{func.returns.canonical_name}`][{func.returns.canonical_path}] instance which contains " |
| 88 |
"the following collection of classes with their assigned names and priorities.\n\n" |
| 89 |
f"{table}" |
| 90 |
) |
| 91 |
|
| 92 |
# Add to docstring. |
| 93 |
if not func.docstring: |
| 94 |
func.docstring = Docstring("", parent=func) |
| 95 |
sections = func.docstring.parsed |
| 96 |
sections.append(DocstringSectionText(body, title="Priority Table")) |