Debian Codegraph @

docs/extensions/conf.py

raw
1 """Sphinx extension for simple configuration value documentation."""
2
3 from __future__ import annotations
4
5 from typing import TYPE_CHECKING, Any, ClassVar
6
7 from docutils import nodes
8 from docutils.parsers.rst import directives
9 from sphinx import addnodes
10 from sphinx.directives import ObjectDescription
11 from sphinx.domains import Domain, ObjType
12 from sphinx.roles import XRefRole
13 from sphinx.util.nodes import make_refnode
14
15 if TYPE_CHECKING:
16 from collections.abc import Iterable, Sequence
17
18 from docutils.nodes import Element
19 from docutils.parsers.rst.states import Inliner
20 from sphinx.addnodes import desc_signature, pending_xref
21 from sphinx.application import Sphinx
22 from sphinx.builders import Builder
23 from sphinx.environment import BuildEnvironment
24 from sphinx.util.typing import ExtensionMetadata, OptionSpec
25
26
27 class Conf(ObjectDescription[str]):
28 """Directive for documenting a single configuration value."""
29
30 option_spec: ClassVar[OptionSpec] = { # type: ignore[misc]
31 "default": directives.unchanged
32 }
33
34 def handle_signature(self, sig: str, signode: desc_signature) -> str:
35 """Process the directive signature (the config name)."""
36 signode += addnodes.desc_name(sig, sig)
37
38 # Add default value if provided
39 if "default" in self.options:
40 signode += nodes.Text(" ")
41 default_container = nodes.inline("", "")
42 default_container += nodes.Text("(default: ")
43 default_container += nodes.literal("", self.options["default"])
44 default_container += nodes.Text(")")
45 signode += default_container
46
47 return sig
48
49 def add_target_and_index(
50 self, name: str, sig: str, signode: desc_signature
51 ) -> None:
52 """Add cross-reference target and index entry."""
53 target = f"conf-{name}"
54 if target not in self.state.document.ids:
55 signode["ids"].append(target)
56 self.state.document.note_explicit_target(signode)
57
58 # A unique full name which includes the document name
59 index_name = f"{self.env.docname.replace('/', '.')}:{name}"
60 # Register with the conf domain
61 domain = self.env.get_domain("conf")
62 domain.data["objects"][index_name] = (self.env.docname, target)
63
64 # Add to index
65 self.indexnode["entries"].append(
66 ("single", f"{name} (configuration value)", target, "", None)
67 )
68
69
70 class ConfDomain(Domain):
71 """Domain for simple configuration values."""
72
73 name = "conf"
74 label = "Simple Configuration"
75 object_types = {"conf": ObjType("conf", "conf")} # noqa: RUF012
76 directives = {"conf": Conf} # noqa: RUF012
77 roles = {"conf": XRefRole()} # noqa: RUF012
78 initial_data: dict[str, Any] = {"objects": {}} # noqa: RUF012
79
80 def get_objects(self) -> Iterable[tuple[str, str, str, str, str, int]]:
81 """Return an iterable of object tuples for the inventory."""
82 for name, (docname, targetname) in self.data["objects"].items():
83 # Remove the document name prefix for display
84 display_name = name.split(":")[-1]
85 yield (name, display_name, "conf", docname, targetname, 1)
86
87 def resolve_xref(
88 self,
89 env: BuildEnvironment,
90 fromdocname: str,
91 builder: Builder,
92 typ: str,
93 target: str,
94 node: pending_xref,
95 contnode: Element,
96 ) -> Element | None:
97 if entry := self.data["objects"].get(target):
98 docname, targetid = entry
99 return make_refnode(
100 builder, fromdocname, docname, targetid, contnode
101 )
102
103 return None
104
105
106 # sphinx.util.typing.RoleFunction
107 def conf_role(
108 name: str,
109 rawtext: str,
110 text: str,
111 lineno: int,
112 inliner: Inliner,
113 /,
114 options: dict[str, Any] | None = None,
115 content: Sequence[str] = (),
116 ) -> tuple[list[nodes.Node], list[nodes.system_message]]:
117 """Role for referencing configuration values."""
118 node = addnodes.pending_xref(
119 "",
120 refdomain="conf",
121 reftype="conf",
122 reftarget=text,
123 refwarn=True,
124 **(options or {}),
125 )
126 node += nodes.literal(text, text.split(":")[-1])
127 return [node], []
128
129
130 def setup(app: Sphinx) -> ExtensionMetadata:
131 app.add_domain(ConfDomain)
132
133 # register a top-level directive so users can use ".. conf:: ..."
134 app.add_directive("conf", Conf)
135
136 # Register role with short name
137 app.add_role("conf", conf_role)
138 return {
139 "version": "0.1",
140 "parallel_read_safe": True,
141 "parallel_write_safe": True,
142 }