|
| 1 | +# This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | +# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | +# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 4 | + |
| 5 | +""" |
| 6 | +Custom autodoc integration for rendering `taskgraph.util.schema.Schema` instances. |
| 7 | +""" |
| 8 | + |
| 9 | +import typing as t |
| 10 | +from textwrap import dedent |
| 11 | +from types import FunctionType, NoneType |
| 12 | + |
| 13 | +from sphinx.ext.autodoc import ClassDocumenter |
| 14 | +from voluptuous import All, Any, Exclusive, Length, Marker, Schema |
| 15 | + |
| 16 | +if t.TYPE_CHECKING: |
| 17 | + from docutils.statemachine import StringList |
| 18 | + |
| 19 | + |
| 20 | +def name(item: t.Any) -> str: |
| 21 | + if isinstance(item, (bool, int, str, NoneType)): |
| 22 | + return str(item) |
| 23 | + |
| 24 | + if isinstance(item, (type, FunctionType)): |
| 25 | + return item.__name__ |
| 26 | + |
| 27 | + if isinstance(item, Length): |
| 28 | + return repr(item) |
| 29 | + |
| 30 | + return item.__class__.__name__ |
| 31 | + |
| 32 | + |
| 33 | +def get_type_str(obj: t.Any) -> tuple[str, bool]: |
| 34 | + # Handle simple subtypes for lists and dicts so that we display |
| 35 | + # `type: dict[str, Any]` inline rather than expanded out at the |
| 36 | + # bottom. |
| 37 | + subtype_str = "" |
| 38 | + if isinstance(obj, (list, Any)): |
| 39 | + items = obj |
| 40 | + if isinstance(items, Any): |
| 41 | + items = items.validators |
| 42 | + |
| 43 | + if all(not isinstance(i, (list, dict, Any)) for i in items): |
| 44 | + subtype_str = f"[{' | '.join(name(i) for i in items)}]" |
| 45 | + |
| 46 | + elif isinstance(obj, dict): |
| 47 | + if all(not isinstance(k, (Marker, Any)) for k in obj.keys()) and all( |
| 48 | + not isinstance(v, (list, dict, Any, All)) for v in obj.values() |
| 49 | + ): |
| 50 | + subtype_str = f"[{' | '.join(name(k) for k in obj.keys())}, {' | '.join({name(v) for v in obj.values()})}]" |
| 51 | + |
| 52 | + return ( |
| 53 | + f"{name(obj)}{subtype_str}", |
| 54 | + bool(subtype_str), |
| 55 | + ) |
| 56 | + |
| 57 | + |
| 58 | +def iter_schema_lines(obj: t.Any, indent: int = 0) -> t.Generator[str, None, None]: |
| 59 | + prefix = " " * indent |
| 60 | + arg_prefix = " " * (indent + 2) |
| 61 | + |
| 62 | + if isinstance(obj, Schema): |
| 63 | + # Display whether extra keys are allowed |
| 64 | + extra = obj._extra_to_name[obj.extra].split("_")[0].lower() |
| 65 | + yield f"{prefix}extra keys: {extra}{'d' if extra[-1] == 'e' else 'ed'}" |
| 66 | + yield "" |
| 67 | + yield from iter_schema_lines(obj.schema, indent) |
| 68 | + return |
| 69 | + |
| 70 | + if isinstance(obj, dict): |
| 71 | + for i, (key, value) in enumerate(obj.items()): |
| 72 | + subtypes_handled = False |
| 73 | + |
| 74 | + # Handle optionally_keyed_by |
| 75 | + keyed_by_str = "" |
| 76 | + if isinstance(value, FunctionType): |
| 77 | + keyed_by_str = ", ".join(getattr(value, "fields", "")) |
| 78 | + value = getattr(value, "schema", value) |
| 79 | + |
| 80 | + # If the key is a marker (aka Required, Optional, Exclusive), |
| 81 | + # display additional information if available, like the |
| 82 | + # description. |
| 83 | + if isinstance(key, Marker): |
| 84 | + # Add marker name and group for Exclusive. |
| 85 | + marker_str = f"{name(key).lower()}" |
| 86 | + if isinstance(key, Exclusive): |
| 87 | + marker_str += f"={key.group_of_exclusion}" |
| 88 | + |
| 89 | + # Make it clear if an allowed value must be constant. |
| 90 | + type_ = "type" |
| 91 | + if isinstance(obj, (bool, int, str, NoneType)): |
| 92 | + type_ = "constant" |
| 93 | + |
| 94 | + # Create the key header + type lines. |
| 95 | + yield f"{prefix}{key.schema} ({marker_str})" |
| 96 | + type_str, subtypes_handled = get_type_str(value) |
| 97 | + yield f"{arg_prefix}{type_}: {type_str}" |
| 98 | + |
| 99 | + # Create the keyed-by line if needed. |
| 100 | + if keyed_by_str: |
| 101 | + yield "" |
| 102 | + yield f"{arg_prefix}optionally keyed by: {keyed_by_str}" |
| 103 | + |
| 104 | + # Create the description if needed. |
| 105 | + if desc := getattr(key, "description", None): |
| 106 | + yield "" |
| 107 | + yield arg_prefix + f"\n{arg_prefix}".join( |
| 108 | + dedent(l) for l in desc.splitlines() |
| 109 | + ) |
| 110 | + |
| 111 | + elif isinstance(key, Any): |
| 112 | + type_str, subtypes_handled = get_type_str(key) |
| 113 | + yield f"{prefix}{type_str}: {name(value)}" |
| 114 | + |
| 115 | + else: |
| 116 | + # If not a marker, simply create a `key: value` line. |
| 117 | + yield f"{prefix}{name(key)}: {name(value)}" |
| 118 | + |
| 119 | + yield "" |
| 120 | + |
| 121 | + # Recurse into values that contain additional schema, unless the |
| 122 | + # types for said containers are simple and we handled them in the |
| 123 | + # type line. |
| 124 | + if isinstance(value, (list, dict, All, Any)) and not subtypes_handled: |
| 125 | + yield from iter_schema_lines(value, indent + 2) |
| 126 | + |
| 127 | + elif isinstance(obj, (list, All, Any)): |
| 128 | + # Recurse into list, All and Any markers. |
| 129 | + op = "or" if isinstance(obj, (list, Any)) else "and" |
| 130 | + if isinstance(obj, (All, Any)): |
| 131 | + obj = obj.validators |
| 132 | + |
| 133 | + for i, item in enumerate(obj): |
| 134 | + if i != 0: |
| 135 | + yield "" |
| 136 | + yield f"{prefix}{op}" |
| 137 | + yield "" |
| 138 | + |
| 139 | + type_, subtypes_handled = get_type_str(item) |
| 140 | + yield f"{arg_prefix}{type_}" |
| 141 | + yield "" |
| 142 | + |
| 143 | + if isinstance(item, (list, dict, All, Any)) and not subtypes_handled: |
| 144 | + yield from iter_schema_lines(item, indent + 2) |
| 145 | + else: |
| 146 | + # Create line for leaf values. |
| 147 | + yield prefix + name(obj) |
| 148 | + yield "" |
| 149 | + |
| 150 | + |
| 151 | +class SchemaDocumenter(ClassDocumenter): |
| 152 | + """ |
| 153 | + Custom Sphinx autodocumenter for instances of `Schema`. |
| 154 | + """ |
| 155 | + |
| 156 | + # Document only `Schema` instances. |
| 157 | + objtype = "schema" |
| 158 | + directivetype = "class" |
| 159 | + content_indent = " " |
| 160 | + |
| 161 | + # Priority over the default ClassDocumenter. |
| 162 | + priority = 10 |
| 163 | + |
| 164 | + @classmethod |
| 165 | + def can_document_member( |
| 166 | + cls, member: object, membername: str, isattr: bool, parent: object |
| 167 | + ) -> bool: |
| 168 | + return isinstance(member, Schema) |
| 169 | + |
| 170 | + def add_directive_header(self, sig: str) -> None: |
| 171 | + super().add_directive_header(sig) |
| 172 | + |
| 173 | + def add_content( |
| 174 | + self, more_content: t.Union["StringList", None], no_docstring: bool = False |
| 175 | + ) -> None: |
| 176 | + # Format schema rules recursively. |
| 177 | + for line in iter_schema_lines(self.object): |
| 178 | + self.add_line(line, "") |
| 179 | + self.add_line("", "") |
0 commit comments