Skip to content
Permalink
Browse files

add rst builder for sphinx

  • Loading branch information...
sdpython committed Jul 12, 2017
1 parent b18e96d commit da040c944e55ae403617f44b529e5bf4370a1ac5
@@ -0,0 +1,167 @@
"""
@brief test log(time=4s)
@author Xavier Dupre
"""

import sys
import os
import unittest

try:
import src
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
os.path.split(__file__)[0],
"..",
"..")))
if path not in sys.path:
sys.path.append(path)
import src

from src.pyquickhelper.loghelper.flog import fLOG
from src.pyquickhelper.pycode import get_temp_folder
from src.pyquickhelper.helpgen import rst2html
from src.pyquickhelper.sphinxext import CmdRef
from src.pyquickhelper.sphinxext.sphinx_cmdref_extension import cmdref_node, visit_cmdref_node, depart_cmdref_node


if sys.version_info[0] == 2:
from codecs import open


class TestRstBuilder(unittest.TestCase):

def test_rst_builder(self):
fLOG(
__file__,
self._testMethodName,
OutputPrint=__name__ == "__main__")

from docutils import nodes as skip_

content = """
test a directive
================
before
.. cmdref::
:title: first cmd
:tag: crypt
:lid: idcmd3
:cmd: src.pyquickhelper.cli.encryption_cli:encrypt
this code shoud appear___
after
""".replace(" ", "")
if sys.version_info[0] >= 3:
content = content.replace('u"', '"')

tives = [("cmdref", CmdRef, cmdref_node,
visit_cmdref_node, depart_cmdref_node)]

html = rst2html(content, # fLOG=fLOG,
writer="rst", keep_warnings=True,
directives=tives, extlinks={'issue': ('http://%s', '_issue_')})

temp = get_temp_folder(__file__, "temp_rst_builder")
with open(os.path.join(temp, "out_cmdref.html"), "w", encoding="utf8") as f:
f.write(html)

t1 = "this code shoud appear"
if t1 not in html:
raise Exception(html)
t1 = "before"
if t1 not in html:
raise Exception(html)

t1 = "after"
if t1 not in html:
raise Exception(html)

t1 = "before"
if t1 not in html:
raise Exception(html)

t1 = "--help"
if t1 not in html:
raise Exception(html)

t1 = '-s STATUS, --status STATUS'
if t1 not in html:
raise Exception(html)

t1 = '.. _idcmd3:'
if t1 not in html:
raise Exception(html)

def test_rst_builder_sphinx(self):
fLOG(
__file__,
self._testMethodName,
OutputPrint=__name__ == "__main__")

from docutils import nodes as skip_

content = """
test a --helpe
================
before
.. cmdref::
:title: first cmd
:tag: freg
:lid: id3
:cmd: src.pyquickhelper.cli.encryption_cli:encrypt
this code shoud appear___
middle
.. cmdreflist::
:tag: freg
:sort: title
after
""".replace(" ", "")
if sys.version_info[0] >= 3:
content = content.replace('u"', '"')

tives = [("cmdref", CmdRef, cmdref_node,
visit_cmdref_node, depart_cmdref_node)]

html = rst2html(content, # fLOG=fLOG,
writer="rst", keep_warnings=True,
directives=tives, layout="sphinx")

temp = get_temp_folder(__file__, "temp_rst_builder_sphinx")
with open(os.path.join(temp, "out_cmdref.html"), "w", encoding="utf8") as f:
f.write(html)

t1 = "this code shoud appear"
if t1 not in html:
raise Exception(html)

t1 = "--help"
if t1 not in html:
raise Exception(html)

t1 = ' -s STATUS, --status STATUS'
if t1 not in html:
raise Exception(html)

t1 = '.. _indexcmdreflistlist-0:'
if t1 not in html:
raise Exception(html)

t1 = '(`original entry <#indexcmdref-freg0>`_ : <string>, line 7)'
if t1 not in html:
raise Exception(html)


if __name__ == "__main__":
unittest.main()
@@ -670,6 +670,7 @@ def custom_setup(app, author):
from ..sphinxext.sphinx_template_extension import setup as setup_tpl
from ..sphinxext.sphinx_cmdref_extension import setup as setup_cmdref
from ..sphinxext.sphinx_epkg_extension import setup as setup_epkg
from ..sphinxext.sphinx_rst_builder import setup as setup_rst

app.connect("autodoc-skip-member", skip)
app.add_config_value('author', author, True)
@@ -690,6 +691,7 @@ def custom_setup(app, author):
setup_docassert(app)
setup_tpl(app)
setup_epkg(app)
setup_rst(app)

# from sphinx.util.texescape import tex_replacements
# tex_replacements += [('oe', '\\oe '), ]
@@ -106,20 +106,19 @@ def default_sphinx_options(fLOG=noLOG, **options):
return res


def rst2html(s, fLOG=noLOG, writer="sphinx", keep_warnings=False,
def rst2html(s, fLOG=noLOG, writer="html", keep_warnings=False,
directives=None, language="en",
layout='docutils', document_name="<<string>>", **options):
"""
Converts a string into HTML format.
@param s string to converts
@param fLOG logging function (warnings will be logged)
@param writer *None* or an instance such as ``HTMLWriterWithCustomDirectives()`` or
``custom`` or ``sphinx``
@param writer ``'html'`` for HTML format or ``'rst'`` for RST format
@param keep_warnings keep_warnings in the final HTML
@param directives new directives to add (see below)
@param language language
@param layout ``docutils``, ``sphinx``, ``sphinx_body``, see below.
@param layout ``'docutils'``, ``'sphinx'``, ``'sphinx_body'``, see below.
@param document_name document name, not really important since the input is a string
@param options Sphinx options see `Render math as images <http://www.sphinx-doc.org/en/stable/ext/math.html#module-sphinx.ext.imgmath>`_,
a subset of options is used, see @see fn default_sphinx_options.
@@ -243,23 +242,29 @@ def depart_node(self, node):
.. versionchanged:: 1.5
More logging is done, the function is more consistent.
Parameter *layout*, *document_name* were added.
Format ``rst`` was added.
"""
if 'html_theme' not in options:
options['html_theme'] = 'basic'
defopt = default_sphinx_options(**options)
if "master_doc" not in defopt:
defopt["master_doc"] = document_name

if writer in ["custom", "sphinx", "HTMLWriterWithCustomDirectives"]:
if writer in ["custom", "sphinx", "HTMLWriterWithCustomDirectives", "html"]:
mockapp, writer, title_names = MockSphinxApp.create(
"sphinx", directives, confoverrides=defopt, fLOG=fLOG)
writer_name = "HTMLWriterWithCustomDirectives"
elif writer == "rst":
mockapp, writer, title_names = MockSphinxApp.create(
"rst", directives, confoverrides=defopt, fLOG=fLOG)
writer_name = "rst"
else:
raise NotImplementedError()
raise ValueError(
"Unexpected writer '{0}', should be 'rst' or 'html'.".format(writer))

if writer is None and directives is not None and len(directives) > 0:
raise NotImplementedError(
"the writer must not be null if custom directives will be added, check the documentation of the fucntion")
"The writer must not be null if custom directives will be added, check the documentation of the fucntion.")

settings_overrides = default_settings.copy()
settings_overrides["warning_stream"] = StringIO()
@@ -391,21 +396,20 @@ def correct_indentation(text):
return text


def docstring2html(function_or_string, format="html", fLOG=noLOG, writer="sphinx",
def docstring2html(function_or_string, format="html", fLOG=noLOG, writer="html",
keep_warnings=False, directives=None, language="en",
layout='docutils', document_name="<string>", **options):
"""
converts a docstring into a HTML format
Converts a docstring into a HTML format.
@param function_or_string function, class, method or doctring
@param format output format (``'html'`` or '``rawhtml``')
@param fLOG logging function
@param writer *None* or an instance such as ``HTMLWriterWithCustomDirectives()`` or
``custom`` or ``sphinx``
@param writer ``'html'`` for HTML format or ``'rst'`` for RST format
@param keep_warnings keep_warnings in the final HTML
@param directives new directives to add (see below)
@param language language
@param layout ``docutils``, ``sphinx``, ``sphinx_body``, see below.
@param layout ``'docutils'``, ``'sphinx'``, ``'sphinx_body'``, see below.
@param document_name document_name for this string
@param options Sphinx options see `Render math as images <http://www.sphinx-doc.org/en/stable/ext/math.html#module-sphinx.ext.imgmath>`_,
a subset of options is used, see @see fn default_sphinx_options.
@@ -441,6 +445,7 @@ def docstring2html(function_or_string, format="html", fLOG=noLOG, writer="sphinx
.. versionchanged:: 1.5
Changed the signature to be like @see fn rst2html.
Format ``rst`` was added.
"""
if not isinstance(function_or_string, str):
doc = function_or_string.__doc__

0 comments on commit da040c9

Please sign in to comment.
You can’t perform that action at this time.