Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a trivial handler for :ref: role when rendering CLI help #3440

Merged
merged 3 commits into from
Jan 27, 2025
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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: Optional[Mapping[str, Any]] = None,
content: Optional[Sequence[str]] = None) \
-> 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
Loading