| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from enum import IntEnum |
| 4 |
from typing import TYPE_CHECKING |
| 5 |
|
| 6 |
from sphinx.ext.autodoc import ClassDocumenter, Documenter, bool_option |
| 7 |
|
| 8 |
if TYPE_CHECKING: |
| 9 |
from typing import Any |
| 10 |
|
| 11 |
from docutils.statemachine import StringList |
| 12 |
|
| 13 |
from sphinx.application import Sphinx |
| 14 |
from sphinx.util.typing import ExtensionMetadata |
| 15 |
|
| 16 |
|
| 17 |
class IntEnumDocumenter(ClassDocumenter): |
| 18 |
objtype = 'intenum' |
| 19 |
directivetype = ClassDocumenter.objtype |
| 20 |
priority = 10 + ClassDocumenter.priority |
| 21 |
option_spec = dict(ClassDocumenter.option_spec) |
| 22 |
option_spec['hex'] = bool_option |
| 23 |
|
| 24 |
@classmethod |
| 25 |
def can_document_member( |
| 26 |
cls, member: Any, membername: str, isattr: bool, parent: Documenter |
| 27 |
) -> bool: |
| 28 |
try: |
| 29 |
return issubclass(member, IntEnum) |
| 30 |
except TypeError: |
| 31 |
return False |
| 32 |
|
| 33 |
def add_directive_header(self, sig: str) -> None: |
| 34 |
super().add_directive_header(sig) |
| 35 |
self.add_line(' :final:', self.get_sourcename()) |
| 36 |
|
| 37 |
def add_content( |
| 38 |
self, |
| 39 |
more_content: StringList | None, |
| 40 |
) -> None: |
| 41 |
super().add_content(more_content) |
| 42 |
|
| 43 |
source_name = self.get_sourcename() |
| 44 |
enum_object: IntEnum = self.object |
| 45 |
use_hex = self.options.hex |
| 46 |
self.add_line('', source_name) |
| 47 |
|
| 48 |
for the_member_name, enum_member in enum_object.__members__.items(): # type: ignore[attr-defined] |
| 49 |
the_member_value = enum_member.value |
| 50 |
if use_hex: |
| 51 |
the_member_value = hex(the_member_value) |
| 52 |
|
| 53 |
self.add_line(f'**{the_member_name}**: {the_member_value}', source_name) |
| 54 |
self.add_line('', source_name) |
| 55 |
|
| 56 |
|
| 57 |
def setup(app: Sphinx) -> ExtensionMetadata: |
| 58 |
app.setup_extension('sphinx.ext.autodoc') # Require autodoc extension |
| 59 |
app.add_autodocumenter(IntEnumDocumenter) |
| 60 |
return { |
| 61 |
'version': '1', |
| 62 |
'parallel_read_safe': True, |
| 63 |
} |