|
| 1 | +""" |
| 2 | +sphinxnotes.dataview |
| 3 | +~~~~~~~~~~~~~~~~~~~~ |
| 4 | +
|
| 5 | +:copyright: Copyright 2025 by the Shengyu Zhang. |
| 6 | +:license: BSD, see LICENSE for details. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | +from typing import Any |
| 11 | + |
| 12 | +from docutils import nodes |
| 13 | +from docutils.parsers.rst import directives |
| 14 | + |
| 15 | +from sphinx.util import logging |
| 16 | +from sphinx.util.docutils import SphinxDirective, SphinxRole |
| 17 | +from sphinx.application import Sphinx |
| 18 | +from sphinx.transforms import SphinxTransform |
| 19 | + |
| 20 | +from . import meta |
| 21 | +from .freestyle import FreeStyleDirective, FreeStyleOptionSpec |
| 22 | +from .data import Data, Field, Schema, Raw |
| 23 | +from .render import Template, Phase, render, JinjaEnv |
| 24 | +from .utils import find_current_document, find_current_section, TempData |
| 25 | +from .context_proxy import proxy |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | + |
| 30 | +class Node(nodes.Element): ... |
| 31 | + |
| 32 | + |
| 33 | +class pending_node(Node, nodes.meta): ... |
| 34 | + |
| 35 | + |
| 36 | +class rendered_node(Node, nodes.container): ... |
| 37 | + |
| 38 | + |
| 39 | +class TemplateStore(TempData[Template]): ... |
| 40 | + |
| 41 | + |
| 42 | +class RawDataStore(TempData[Raw]): ... |
| 43 | + |
| 44 | + |
| 45 | +class SchemaStore(TempData[Schema]): ... |
| 46 | + |
| 47 | + |
| 48 | +class TemplateDirective(SphinxDirective): |
| 49 | + option_spec = { |
| 50 | + 'on': Phase.option_spec, |
| 51 | + 'debug': directives.flag, |
| 52 | + } |
| 53 | + has_content = True |
| 54 | + |
| 55 | + def run(self) -> list[nodes.Node]: |
| 56 | + self.assert_has_content() |
| 57 | + |
| 58 | + tmpl = Template( |
| 59 | + text='\n'.join(self.content), |
| 60 | + phase=self.options.get('on', Phase.default()), |
| 61 | + debug='debug' in self.options, |
| 62 | + ) |
| 63 | + TemplateStore.set(self.state.document, tmpl) |
| 64 | + |
| 65 | + return [] |
| 66 | + |
| 67 | + |
| 68 | +class DataSchemaDirective(FreeStyleDirective): |
| 69 | + optional_arguments = 1 |
| 70 | + option_spec = FreeStyleOptionSpec() |
| 71 | + has_content = True |
| 72 | + |
| 73 | + def run(self) -> list[nodes.Node]: |
| 74 | + if self.arguments: |
| 75 | + name = Field.from_str(self.arguments[0]) |
| 76 | + else: |
| 77 | + name = None |
| 78 | + |
| 79 | + attrs = {} |
| 80 | + for k, v in self.options.items(): |
| 81 | + attrs[k] = Field.from_str(v) |
| 82 | + |
| 83 | + if self.content: |
| 84 | + content = Field.from_str(self.content[0]) |
| 85 | + else: |
| 86 | + content = None |
| 87 | + |
| 88 | + schema = Schema(name, attrs, content) |
| 89 | + SchemaStore.set(self.state.document, schema) |
| 90 | + |
| 91 | + return [] |
| 92 | + |
| 93 | + |
| 94 | +def markup_context(v: SphinxDirective | SphinxRole | nodes.Element) -> dict[str, Any]: |
| 95 | + ctx = {} |
| 96 | + |
| 97 | + if isinstance(v, nodes.Element): |
| 98 | + ctx['_markup'] = {} |
| 99 | + else: |
| 100 | + isdir = isinstance(v, SphinxDirective) |
| 101 | + ctx['_markup'] = { |
| 102 | + 'type': 'directive' if isdir else 'role', |
| 103 | + 'name': v.name, |
| 104 | + 'lineno': v.lineno, |
| 105 | + 'rawtext': v.block_text if isdir else v.rawtext, |
| 106 | + } |
| 107 | + return ctx |
| 108 | + |
| 109 | + |
| 110 | +def doctree_context(v: SphinxDirective | SphinxRole | nodes.Element) -> dict[str, Any]: |
| 111 | + ctx = {} |
| 112 | + if isinstance(v, nodes.Element): |
| 113 | + ctx['_doc'] = proxy(find_current_document(v)) |
| 114 | + ctx['_section'] = proxy(find_current_section(v)) |
| 115 | + else: |
| 116 | + isdir = isinstance(v, SphinxDirective) |
| 117 | + state = v.state if isdir else v.inliner |
| 118 | + ctx['_doc'] = proxy(state.document) |
| 119 | + ctx['_section'] = proxy(find_current_section(state.parent)) |
| 120 | + return ctx |
| 121 | + |
| 122 | + |
| 123 | +def sphinx_context(v: SphinxDirective | SphinxRole | SphinxTransform) -> dict[str, Any]: |
| 124 | + ctx = {} |
| 125 | + ctx['_env'] = proxy(v.env) |
| 126 | + ctx['_config'] = proxy(v.config) |
| 127 | + return ctx |
| 128 | + |
| 129 | + |
| 130 | +class DataDefineDirective(FreeStyleDirective): |
| 131 | + optional_arguments = 1 |
| 132 | + has_content = True |
| 133 | + |
| 134 | + def run(self) -> list[nodes.Node]: |
| 135 | + tmpl = TemplateStore.get(self.state.document) |
| 136 | + if tmpl is None: |
| 137 | + return [] |
| 138 | + |
| 139 | + schema = SchemaStore.get(self.state.document) |
| 140 | + rawdata = self._raw_data() |
| 141 | + |
| 142 | + if tmpl.phase != Phase.Parsing: |
| 143 | + n = pending_node() |
| 144 | + RawDataStore.set(n, rawdata) |
| 145 | + TemplateStore.set(n, tmpl) |
| 146 | + if schema: |
| 147 | + SchemaStore.set(n, schema) |
| 148 | + return [n] |
| 149 | + |
| 150 | + if schema: |
| 151 | + try: |
| 152 | + data = schema.parse(rawdata) |
| 153 | + except ValueError as e: |
| 154 | + raise self.error(str(e)) |
| 155 | + else: |
| 156 | + data = Data.from_raw(rawdata) |
| 157 | + |
| 158 | + extra_ctx = { |
| 159 | + **sphinx_context(self), |
| 160 | + **doctree_context(self), |
| 161 | + **markup_context(self), |
| 162 | + } |
| 163 | + n = render(self.parse_text_to_nodes, tmpl, data, extra_ctx) |
| 164 | + |
| 165 | + return [n] |
| 166 | + |
| 167 | + def _raw_data(self) -> Raw: |
| 168 | + return Raw( |
| 169 | + self.arguments[0] if self.arguments else None, |
| 170 | + self.options.copy(), |
| 171 | + '\n'.join(self.content), |
| 172 | + ) |
| 173 | + |
| 174 | + |
| 175 | +class ParsedHookDirective(SphinxDirective): |
| 176 | + def run(self) -> list[nodes.Node]: |
| 177 | + for pending in self.state.document.findall(pending_node): |
| 178 | + tmpl = TemplateStore.get(pending) |
| 179 | + schema = SchemaStore.get(pending) |
| 180 | + rawdata = RawDataStore.get(pending) |
| 181 | + |
| 182 | + assert tmpl |
| 183 | + assert rawdata |
| 184 | + |
| 185 | + if schema: |
| 186 | + try: |
| 187 | + data = schema.parse(rawdata) |
| 188 | + except ValueError as e: |
| 189 | + raise self.error(str(e)) |
| 190 | + else: |
| 191 | + data = Data.from_raw(rawdata) |
| 192 | + |
| 193 | + extra_ctx = { |
| 194 | + **sphinx_context(self), |
| 195 | + **doctree_context(pending), |
| 196 | + **markup_context(pending), |
| 197 | + } |
| 198 | + n = render(self.parse_text_to_nodes, tmpl, data, extra_ctx) |
| 199 | + pending.replace_self(n) |
| 200 | + |
| 201 | + return [] # nothing to return |
| 202 | + |
| 203 | + |
| 204 | +def on_source_read(app, docname, content): |
| 205 | + # NOTE: content is a single element list, representing the content of the |
| 206 | + # source file. |
| 207 | + # |
| 208 | + # .. seealso:: https://www.sphinx-doc.org/en/master/extdev/event_callbacks.html#event-source-read |
| 209 | + content[-1] = content[-1] + '\n\n.. data:parsed-hook::' |
| 210 | + |
| 211 | + |
| 212 | +class ResolvingHookTransform(SphinxTransform): |
| 213 | + default_priority = 210 # 在主要处理阶段运行 |
| 214 | + |
| 215 | + def apply(self, **kwargs): |
| 216 | + for pending in self.document.findall(pending_node): |
| 217 | + tmpl = TemplateStore.get(pending) |
| 218 | + schema = SchemaStore.get(pending) |
| 219 | + rawdata = RawDataStore.get(pending) |
| 220 | + |
| 221 | + assert tmpl |
| 222 | + assert rawdata |
| 223 | + |
| 224 | + if schema: |
| 225 | + try: |
| 226 | + data = schema.parse(rawdata) |
| 227 | + except ValueError: |
| 228 | + continue # FIXME |
| 229 | + else: |
| 230 | + data = Data.from_raw(rawdata) |
| 231 | + |
| 232 | + n = render(self.parse_text_to_nodes, tmpl, data, {}) |
| 233 | + pending.replace_self(n) |
| 234 | + |
| 235 | + |
| 236 | +def setup(app: Sphinx): |
| 237 | + meta.pre_setup(app) |
| 238 | + |
| 239 | + app.add_directive('data:tmpl', TemplateDirective, False) |
| 240 | + app.add_directive('data:schema', DataSchemaDirective, False) |
| 241 | + # app.add_directive('data:use-tmpl', DataTemplateDirective, False) |
| 242 | + app.add_directive('data:def', DataDefineDirective, False) |
| 243 | + app.add_directive('data:parsed-hook', ParsedHookDirective, False) |
| 244 | + |
| 245 | + app.connect('source-read', on_source_read) |
| 246 | + |
| 247 | + app.add_transform(ResolvingHookTransform) |
| 248 | + |
| 249 | + JinjaEnv.setup(app) |
| 250 | + |
| 251 | + return meta.post_setup(app) |
0 commit comments