2024-07-19 06:16:59 -03:00
|
|
|
"""Feature search results for glossary items prominently."""
|
2020-12-18 15:00:51 -04:00
|
|
|
|
2024-07-19 06:16:59 -03:00
|
|
|
from __future__ import annotations
|
2020-12-18 15:00:51 -04:00
|
|
|
|
2021-04-08 19:07:01 -03:00
|
|
|
import json
|
2024-07-19 06:16:59 -03:00
|
|
|
from pathlib import Path
|
|
|
|
from typing import TYPE_CHECKING
|
|
|
|
|
|
|
|
from docutils import nodes
|
2020-12-18 15:00:51 -04:00
|
|
|
from sphinx.addnodes import glossary
|
|
|
|
from sphinx.util import logging
|
|
|
|
|
2024-07-19 06:16:59 -03:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from sphinx.application import Sphinx
|
|
|
|
from sphinx.util.typing import ExtensionMetadata
|
2020-12-18 15:00:51 -04:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2024-07-19 08:48:53 -03:00
|
|
|
def process_glossary_nodes(
|
|
|
|
app: Sphinx,
|
|
|
|
doctree: nodes.document,
|
|
|
|
_docname: str,
|
|
|
|
) -> None:
|
2024-05-10 07:24:02 -03:00
|
|
|
if app.builder.format != 'html' or app.builder.embedded:
|
2020-12-18 15:00:51 -04:00
|
|
|
return
|
|
|
|
|
2024-07-19 06:16:59 -03:00
|
|
|
if hasattr(app.env, 'glossary_terms'):
|
|
|
|
terms = app.env.glossary_terms
|
|
|
|
else:
|
|
|
|
terms = app.env.glossary_terms = {}
|
2020-12-18 15:00:51 -04:00
|
|
|
|
2024-05-23 23:04:12 -03:00
|
|
|
for node in doctree.findall(glossary):
|
2024-07-19 06:16:59 -03:00
|
|
|
for glossary_item in node.findall(nodes.definition_list_item):
|
|
|
|
term = glossary_item[0].astext()
|
|
|
|
definition = glossary_item[-1]
|
2020-12-18 15:00:51 -04:00
|
|
|
|
|
|
|
rendered = app.builder.render_partial(definition)
|
2024-07-19 06:16:59 -03:00
|
|
|
terms[term.lower()] = {
|
|
|
|
'title': term,
|
2024-07-19 08:48:53 -03:00
|
|
|
'body': rendered['html_body'],
|
2020-12-18 15:00:51 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2024-07-19 06:16:59 -03:00
|
|
|
def write_glossary_json(app: Sphinx, _exc: Exception) -> None:
|
|
|
|
if not getattr(app.env, 'glossary_terms', None):
|
2020-12-18 15:00:51 -04:00
|
|
|
return
|
|
|
|
|
2024-07-19 08:48:53 -03:00
|
|
|
logger.info('Writing glossary.json', color='green')
|
2024-07-19 06:16:59 -03:00
|
|
|
dest = Path(app.outdir, '_static', 'glossary.json')
|
|
|
|
dest.parent.mkdir(exist_ok=True)
|
|
|
|
dest.write_text(json.dumps(app.env.glossary_terms), encoding='utf-8')
|
2020-12-18 15:00:51 -04:00
|
|
|
|
|
|
|
|
2024-07-19 06:16:59 -03:00
|
|
|
def setup(app: Sphinx) -> ExtensionMetadata:
|
2020-12-18 15:00:51 -04:00
|
|
|
app.connect('doctree-resolved', process_glossary_nodes)
|
2024-07-19 06:16:59 -03:00
|
|
|
app.connect('build-finished', write_glossary_json)
|
2020-12-18 15:00:51 -04:00
|
|
|
|
2024-07-19 06:16:59 -03:00
|
|
|
return {
|
|
|
|
'version': '1.0',
|
|
|
|
'parallel_read_safe': True,
|
|
|
|
'parallel_write_safe': True,
|
|
|
|
}
|