Source code for taika.ext.rst

"""
:mod:`taika.ext.rst` -- ReStructuredText
========================================

This extension parses the content of the documents into HTML using ReStructuredText specifications.

Trigger
-------

This extension is subscribed to the "doc-post-read" event.

Frontmatter
-----------

None.

Process
-------

#. Reads the suffix of `path` and if it matches, process the document.
#. Modifies the suffix of `url` path to ".html".
#. Process the content with :func:`docutils.publish_parts` and replaces it with the "body" part.
#. Done!

Configuration
-------------

.. note::

    All configuration hangs from a key in the YML configuration named 'restructuredtext'.
    Inside it, you can add the following options:

.. data:: suffixes (list)

    Default: **[.rst]**

    Tells the parser to ONLY modify docs with that suffix. Otherwise the document is ignored.
    This is checked against the source path (`path`), not the destination path (`url`).

.. data:: strict (bool)

    Default: **True**

    Exits with error code 1 if there is any warning or error when parsing files.


.. data:: options (dict)

    Default:
        | { stylesheet_path: '',
        | halt_level: 1,
        | traceback: True,
        | report_level: 5,
        | syntax_highlight: 'short',
        | doctitle_xform: False }

    You can check the available options at `HTML writer documentation
    <http://docutils.sourceforge.net/docs/user/config.html#html4css1-writer>`_


Functions
---------
"""
import copy
import logging
import sys
from io import StringIO

from .. import utils

try:
    from docutils.core import publish_parts
    from docutils.utils import SystemMessage
except ImportError:
    print("'taika.ext.rst' needs the package 'docutils' to be installed.")
    sys.exit(1)

RESTRUCTUREDTEXT = {
    "suffixes": [".rst"],
    "strict": True,
    "options": {
        "stylesheet_path": "",
        "halt_level": 1,
        "traceback": True,
        "report_level": 5,
        "syntax_highlight": "short",
        "doctitle_xform": False,
    },
}

LOGGER = logging.getLogger(__name__)


[docs]def parse_rst(site, document): """Parse ``content`` and modify ``url`` keys of `document`. Parameters ---------- site : :class:`taika.taika.Taika` The Taika site. document : dict The document to be parsed. """ user_config = site.config.get("restructuredtext", {}) config = utils.merge(user_config, copy.deepcopy(RESTRUCTUREDTEXT)) suffixes = config["suffixes"] options = config["options"] strict = config["strict"] if document["path"].suffix not in suffixes: return document["url"] = document["url"].with_suffix(".html") warning_stream = StringIO() options["warning_stream"] = warning_stream try: html = publish_parts( source=document["content"], source_path=site.source / document["path"], writer_name="html5", settings_overrides=options, )["body"] document["content"] = html except SystemMessage: msg = warning_stream.getvalue().strip("\n").replace("\n", " ") if strict: action = "Exiting" LOGGER.critical(f"Problem when parsing a file. Error message: '{msg}' {action}...") sys.exit(1) else: action = f"Skipping, 'rst_strict' = {strict}" LOGGER.warning(f"Problem when parsing a file. Error message: '{msg}' {action}...")
[docs]def setup(site): site.events.register("doc-post-read", parse_rst)