Skip to content

Commit

Permalink
Add a trivial handler for :ref: role when rendering CLI help
Browse files Browse the repository at this point in the history
Sphinx takes care of it when building (HTML) docs, but for CLI help, we
need to provide a handler of our own. But even a simple one is enough.
  • Loading branch information
happz committed Jan 2, 2025
1 parent 01d38b8 commit cc5f92f
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion tmt/utils/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@
"""

import functools
from typing import Optional
from collections.abc import Mapping, Sequence
from typing import Any, Optional

import click
import docutils.frontend
import docutils.nodes
import docutils.parsers.rst
import docutils.parsers.rst.roles
import docutils.parsers.rst.states
import docutils.utils

import tmt.log
Expand Down Expand Up @@ -259,9 +262,39 @@ def unknown_departure(self, node: docutils.nodes.Node) -> None:
raise GeneralError(f"Unhandled ReST node '{node}'.")


# Role handling works out of the box when building docs with Sphinx, but
# for CLI rendering, we use docutils directly, and we need to provide
# handlers for roles supported by Sphinx.
#
# It might be possible to reuse Sphinx implementation, but a brief
# reading of Sphinx source gives an impression of pretty complex code.
# And we don't need anything fancy, how hard could it be, right? See
# https://docutils.sourceforge.io/docs/howto/rst-roles.html
def role_ref(
name: str,
rawtext: str,
text: str,
lineno: int,
inliner: docutils.parsers.rst.states.Inliner,
options: Mapping[str, Any],
content: Sequence[str]) \
-> tuple[Sequence[docutils.nodes.reference], Sequence[docutils.nodes.reference]]:
"""
A handler for ``:ref:`` role.
:returns: a simple :py:class:`docutils.nodes.Text` node with text of
the "link": ``foo`` for both ``:ref:`foo``` and
``:ref:`foo</bar>```.
"""

return ([docutils.nodes.reference(rawtext, text)], [])


def parse_rst(text: str) -> docutils.nodes.document:
""" Parse a ReST document into docutils tree of nodes """

docutils.parsers.rst.roles.register_local_role('ref', role_ref)

parser = docutils.parsers.rst.Parser()
components = (docutils.parsers.rst.Parser,)
settings = docutils.frontend.OptionParser(components=components).get_default_values()
Expand Down

0 comments on commit cc5f92f

Please sign in to comment.