Exemplo n.º 1
0
    def run(self):

        docdir = op.join(basedir, 'doc')
        destdir = op.join(docdir, 'html')

        if op.exists(destdir):
            shutil.rmtree(destdir)

        print('Building documentation [{}]'.format(destdir))

        import sphinx.cmd.build as sphinx_build

        try:
            import unittest.mock as mock
        except Exception:
            import mock

        mockobj = mock.MagicMock()
        mockedModules = open(op.join(docdir, 'mock_modules.txt')).readlines()
        mockedClasses = open(op.join(docdir, 'mock_classes.txt')).readlines()

        mockedModules = [l.strip() for l in mockedModules]
        mockedClasses = [l.strip() for l in mockedClasses]
        mockedModules = {m: mockobj for m in mockedModules}

        patches = [mock.patch.dict('sys.modules', **mockedModules)] + \
                  [mock.patch('wx.lib.newevent.NewEvent',
                              return_value=(mockobj, mockobj))] + \
                  [mock.patch(c, object) for c in mockedClasses]

        [p.start() for p in patches]
        sphinx_build.main([docdir, destdir])
        [p.stop() for p in patches]
Exemplo n.º 2
0
    def run(self):

        docdir  = op.join(basedir, 'doc')
        destdir = op.join(docdir, 'html')

        if op.exists(destdir):
            shutil.rmtree(destdir)

        print('Building documentation [{}]'.format(destdir))

        import sphinx.cmd.build as sphinx_build

        try:
            import unittest.mock as mock
        except:
            import mock

        mockobj       = mock.MagicMock()
        mockobj.__version__ = '2.2.0'
        mockedModules = open(op.join(docdir, 'mock_modules.txt')).readlines()
        mockedModules = [l.strip()   for l in mockedModules]
        mockedModules = {m : mockobj for m in mockedModules}

        patches = [mock.patch.dict('sys.modules', **mockedModules)]

        [p.start() for p in patches]
        sphinx_build.main([docdir, destdir])
        [p.stop() for p in patches]
def test_autodoc_of_c_file(tmp_path):
    """
    Tests the creation of the documented C file.
    """
    source_dir = os.path.join(SCRIPT_DIR, "..", "assets")
    main(["-a", "-E", "-W", source_dir, str(tmp_path)])

    file_name = tmp_path / "example.html"
    with file_name.open() as f:
        contents = f.read()

    assert "This is a file comment" in contents

    # Check for anonymouse enums
    assert "anon_example_" in contents

    # Check for a bug where typedefed enums showed up as anonymouse and the
    # typedef.
    occurences = len(re.findall("THE_LAST_ENUM", contents))
    occurences //= 4  # The id, text, anchor, link to source file
    assert occurences == 1

    file_name = tmp_path / "sub_dir" / "file_2.html"
    with file_name.open() as f:
        contents = f.read()

    # Not ideal to have multiple asserts in one test, but sphinx takes a while
    # to run...
    assert "This is file 2" in contents
    assert "It has a multi-line comment" in contents
    assert "unknown_member" in contents
def test_builds_correctly(
    cookies,
    test_input_context: Dict[str, str],
    test_input_repository_hosting_platform: str,
    test_input_organisational_framework: str,
    test_input_using_r: str,
) -> None:
    """Test that the projects are built correctly with no errors."""

    # Create a new project adding extra context
    test_output_project = cookies.bake(
        extra_context={
            **test_input_context,
            "repository_hosting_platform": test_input_repository_hosting_platform,
            "organisational_framework": test_input_organisational_framework,
            "using_R": test_input_using_r,
        }
    )

    # Check that the build passes
    assert test_output_project.exit_code == 0
    assert test_output_project.exception is None

    # Check there are no `cookiecutter.variable_name` entries in any file
    all_files = [f for f in test_output_project.project_path.rglob("*") if f.is_file()]
    for file in all_files:
        try:
            with open(file, encoding="utf-8") as f:
                assert re.search(r"{+ ?cookiecutter\.\w+ ?}+", f.read()) is None
        except UnicodeDecodeError:
            continue

    # Test that the documentation builds as expected, and then for broken links
    test_output_project_docs_folder = test_output_project.project_path.joinpath("docs")
    assert (
        main(
            [
                "-b",
                "html",
                str(test_output_project_docs_folder),
                str(test_output_project_docs_folder.joinpath("_build")),
            ]
        )
        == 0
    )
    assert (
        main(
            [
                "-b",
                "linkcheck",
                str(test_output_project_docs_folder),
                str(test_output_project_docs_folder.joinpath("_linkcheck")),
            ]
        )
        == 0
    )
Exemplo n.º 5
0
 def generate_documentation(self):
     """
     Runs sphinx on the project using the default conf.py file in the source
     directory.
     """
     self.generate_api_docs()
     build.main([
         self.SOURCE_DIR,
         self.BUILD_DIR,
     ])
Exemplo n.º 6
0
def main():
    options = """
    -b html {sourcedir}  {builddir}/html {sphinxopts}
    """.format(
        sourcedir="source",
        builddir=os.path.join(os.getcwd(), "build"),
        paperopt="-D latex_paper_size=letter",
        sphinxopts="",
    ).strip()

    build.main(options.split())
Exemplo n.º 7
0
    def run(self):
        import sphinx.cmd.build as sphinx_build

        basedir = op.dirname(__file__)
        docdir = op.join(basedir, 'doc')
        destdir = op.join(docdir, 'html')

        if op.exists(destdir):
            shutil.rmtree(destdir)

        print('Building documentation [{}]'.format(destdir))

        sphinx_build.main([docdir, destdir])
Exemplo n.º 8
0
    def run(self):

        if not _HAVE_SPHINX:
            raise RuntimeError(
                "You must install Sphinx to build or test the documentation.")

        if self.test:
            path = os.path.join(
                os.path.abspath('.'), "doc", "_build", "doctest")
            mode = "doctest"
        else:
            path = os.path.join(
                os.path.abspath('.'), "doc", "_build", version)
            mode = "html"

            try:
                os.makedirs(path)
            except:
                pass

        sphinx_args = ["-E", "-b", mode, "doc", path]

        if hasattr(sphinx, 'build_main'):
            status = sphinx.build_main(sphinx_args)
        else:
            status = sphinx.main(sphinx_args)

        if status:
            raise RuntimeError("documentation step '%s' failed" % (mode,))

        sys.stdout.write("\nDocumentation step '%s' performed, results here:\n"
                         "   %s/\n" % (mode, path))
Exemplo n.º 9
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    warnings.warn(
        'sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
        RemovedInSphinx30Warning,
        stacklevel=2)
    return build.main(argv)
Exemplo n.º 10
0
        def run(self):
            # Run in-place build before Sphinx doc build.
            ret = subprocess.call(
                [sys.executable, sys.argv[0], 'build_ext', '-i'])
            if ret != 0:
                raise RuntimeError("Building BSON-Numpy failed!")

            if not HAVE_SPHINX:
                raise RuntimeError("You must install Sphinx to build or test "
                                   "the documentation.")

            if self.test:
                path = os.path.join(
                    os.path.abspath('.'), "doc", "_build", "doctest")
                mode = "doctest"
            else:
                path = os.path.join(
                    os.path.abspath('.'), "doc", "_build", version)
                mode = "html"

                try:
                    os.makedirs(path)
                except:
                    pass

            sphinx_args = ["-E", "-b", mode, "doc", path]
            status = sphinxbuild.main(sphinx_args)

            if status:
                raise RuntimeError("Documentation step '%s' failed" % (mode,))

            msg = "\nDocumentation step '{}' performed, results here:\n   {}\n"
            sys.stdout.write(msg.format(mode, path))
Exemplo n.º 11
0
    def test_build(self) -> None:
        """Try building the docs and see if it works."""

        # Remove the build directory if it exists.
        if os.path.isdir(os.path.join(self.docs_dir, "build/")):
            shutil.rmtree(os.path.join(self.docs_dir, "build/"))

        # Copy the environment and set the SPHINXBUILD variable to call the module.
        # This is for it to work properly with GitHub Workflows
        env = os.environ.copy()
        env["SPHINXBUILD"] = f"{sys.executable} -m sphinx"

        # Run sphinx-buil
        main([
            os.path.join(self.docs_dir, "source"),
            os.path.join(self.docs_dir, "build")
        ])
Exemplo n.º 12
0
    def run(self):

        docdir = self.docdir
        destdir = op.join(docdir, 'html')

        if op.exists(destdir):
            shutil.rmtree(destdir)

        import sphinx.cmd.build as sphinx_build

        try:
            import unittest.mock as mock
        except ImportError:
            import mock

        # Sigh. Why can't I mock a package?
        mockobj = mock.MagicMock()
        mockedModules = open(op.join(docdir, 'mock_modules.txt')).readlines()
        mockedClasses = open(op.join(docdir, 'mock_classes.txt')).readlines()
        mockedModules = {m.strip(): mockobj for m in mockedModules}
        mockedClasses = {l.strip(): None for l in mockedClasses}

        # a different mock class for each mocked class
        for clsname in mockedClasses.keys():

            class MockClass(object):
                def __init__(self, *args, **kwargs):
                    pass

            mockedClasses[clsname] = MockClass

        class MockType(type):
            pass

        patches = [mock.patch.dict('sys.modules', **mockedModules)]    + \
                  [mock.patch('wx.lib.newevent.NewEvent',
                              return_value=(mockobj, mockobj))]        + \
                  [mock.patch(n, c) for n, c in mockedClasses.items()] + \
                  [mock.patch('fsleyes_props.PropertyOwner', MockType)]

        [p.start() for p in patches]
        sphinx_build.main([docdir, destdir])
        [p.stop() for p in patches]
Exemplo n.º 13
0
def build_html_parallel(args):
    """функция конвертации для указанной папки, которая запускается параллельно
    :param args: параметры сборки
    """

    mode, dir_name, build_dir = args

    print('start', mode, dir_name)

    stdout = StringIO()
    stderr = StringIO()

    stdout_def = sys.stdout
    stderr_def = sys.stderr

    sys.stdout = stdout
    sys.stderr = stderr

    build_params = [
        # укажем папку с конфигом по умолчанию
        '-c',
        BASE_DIR,
        # укажем формат конвертируемых данных
        '-b',
        mode,
        # укажем папку обработки
        os.path.join(BASE_DIR, dir_name),
        # укажем папку выгрузки
        os.path.join(build_dir, dir_name),
    ]

    build.main(build_params)

    sys.stdout = stdout_def
    sys.stderr = stderr_def

    print('done', mode, dir_name)

    # возвращаем результата
    return stdout.getvalue(), stderr.getvalue()
def test_incremental_build_updates_docs(tmp_path):
    """
    Tests the output is updated if one of the input files to document is
    changed.
    """
    original_source_dir = os.path.join(SCRIPT_DIR, "..", "assets")

    # Copy over all the documentation source files as this is going to modify
    # one of them
    new_source_path = tmp_path / "assets"
    new_source_dir = str(new_source_path)
    shutil.copytree(original_source_dir, new_source_dir)

    output_path = tmp_path / "_build"

    # Use `-a`, `-E` initially to ensure an initial full clean build
    main(["-a", "-E", "-W", new_source_dir, str(output_path)])

    file_name = output_path / "example.html"
    with file_name.open() as f:
        contents = f.read()

    new_expected_contents = "A new update to a file."

    # Pre-condition check, if this isn't True then the next check may be
    # invalid.
    assert "This is a file comment" in contents
    assert new_expected_contents not in contents

    source_name = new_source_path / "c_source" / "example.c"
    with source_name.open("w") as f:
        f.write(f"/** {new_expected_contents} */")

    main(["-W", new_source_dir, str(output_path)])

    with file_name.open() as f:
        contents = f.read()

    assert new_expected_contents in contents
Exemplo n.º 15
0
def ablog_build(
    builder=None,
    sourcedir=None,
    website=None,
    doctrees=None,
    traceback=False,
    runpdb=False,
    allfiles=False,
    werror=False,
    verbosity=0,
    quiet=False,
    extra_quiet=False,
    no_colors=False,
    **kwargs,
):
    confdir = find_confdir(sourcedir)
    conf = read_conf(confdir)
    website = website or os.path.join(confdir,
                                      getattr(conf, "ablog_website", BUILDDIR))
    doctrees = doctrees or os.path.join(
        confdir, getattr(conf, "ablog_doctrees", DOCTREES))
    sourcedir = sourcedir or confdir
    argv = sys.argv[:1]
    argv.extend(["-b", builder or getattr(conf, "ablog_builder", "dirhtml")])
    argv.extend(["-d", doctrees])
    if traceback:
        argv.extend(["-T"])
    if runpdb:
        argv.extend(["-P"])
    if allfiles:
        argv.extend(["-a"])
    if werror:
        argv.extend(["-W"])
    if verbosity > 0:
        argv.extend(["-v"] * verbosity)
    if quiet:
        argv.extend(["-q"])
    if extra_quiet:
        argv.extend(["-Q"])
    if no_colors:
        argv.extend(["-N"])
    argv.extend([sourcedir, website])

    from sphinx.cmd.build import main

    sys.exit(main(argv[1:]))
Exemplo n.º 16
0
    def run(self):

        if not _HAVE_SPHINX:
            raise RuntimeError(
                "You must install Sphinx to build or test the documentation.")

        if sys.version_info[0] >= 3:
            import doctest
            from doctest import OutputChecker as _OutputChecker

            # Match u or U (possibly followed by r or R), removing it.
            # r/R can follow u/U but not precede it. Don't match the
            # single character string 'u' or 'U'.
            _u_literal_re = re.compile(r"(\W|^)(?<![\'\"])[uU]([rR]?[\'\"])",
                                       re.UNICODE)
            # Match b or B (possibly followed by r or R), removing.
            # r/R can follow b/B but not precede it. Don't match the
            # single character string 'b' or 'B'.
            _b_literal_re = re.compile(r"(\W|^)(?<![\'\"])[bB]([rR]?[\'\"])",
                                       re.UNICODE)

            class _StringPrefixFixer(_OutputChecker):
                def check_output(self, want, got, optionflags):
                    # The docstrings are written with python 2.x in mind.
                    # To make the doctests pass in python 3 we have to
                    # strip the 'u' prefix from the expected results. The
                    # actual results won't have that prefix.
                    want = re.sub(_u_literal_re, r'\1\2', want)
                    # We also have to strip the 'b' prefix from the actual
                    # results since python 2.x expected results won't have
                    # that prefix.
                    got = re.sub(_b_literal_re, r'\1\2', got)
                    return super(_StringPrefixFixer,
                                 self).check_output(want, got, optionflags)

                def output_difference(self, example, got, optionflags):
                    example.want = re.sub(_u_literal_re, r'\1\2', example.want)
                    got = re.sub(_b_literal_re, r'\1\2', got)
                    return super(_StringPrefixFixer, self).output_difference(
                        example, got, optionflags)

            doctest.OutputChecker = _StringPrefixFixer

        if self.test:
            path = os.path.join(os.path.abspath('.'), "doc", "_build",
                                "doctest")
            mode = "doctest"
        else:
            path = os.path.join(os.path.abspath('.'), "doc", "_build", version)
            mode = "html"

            try:
                os.makedirs(path)
            except:
                pass

        sphinx_args = ["-E", "-b", mode, "doc", path]

        # sphinx.main calls sys.exit when sphinx.build_main exists.
        # Call build_main directly so we can check status and print
        # the full path to the built docs.
        if hasattr(sphinx, 'build_main'):
            status = sphinx.build_main(sphinx_args)
        else:
            status = sphinx.main(sphinx_args)

        if status:
            raise RuntimeError("documentation step '%s' failed" % (mode, ))

        sys.stdout.write("\nDocumentation step '%s' performed, results here:\n"
                         "   %s/\n" % (mode, path))
Exemplo n.º 17
0
# Copyright 2019 Tulip Solutions B.V.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys
"""Wraps `sphinx-build`, taking first argument as path to the bazel-out/stable-status.txt file which is consumed in
`conf.py`. All other arguments are passed on to `sphinx-build`.
"""

if __name__ == "__main__":
    os.environ['BAZEL_STABLE_STATUS_FILE'] = os.path.abspath(sys.argv[1])
    # 'Sniff' the sources input directory as a way to know what it would be a configuration-time in conf.py.
    # Needed for pointing to custom CSS/JS.
    os.environ['BAZEL_SPHINX_INPUT_DIR'] = os.path.abspath(sys.argv[-2])

    from sphinx.cmd.build import main
    sys.exit(main(sys.argv[2:]))
Exemplo n.º 18
0
              for name, value in [a.partition('=')[::2]]
              if name == BROWSER_OPEN and value}
    if values:
        if len(values) != 1:
            raise ValueError(f'conflicting {BROWSER_OPEN}: {values}')
        value, = values
        if value:
            open_result = open_result.parent / value
    args = [a for a in args if a.partition('=')[0] != BROWSER_OPEN]

if not args:  # no pytest args given
    args = [a for a in DEFAULT_ARGS
            if a != SKIP_OPEN_RESULT and a.partition('=')[0] != BROWSER_OPEN]

if args == ['-b', 'doctest']:
    args += ['-W', str(SOURCE), str(SOURCE / '_doctest')]

print('', f'sphinx.cmd.build.main({args})',)
returncode = build.main(args)
print('', f'returncode: {returncode!r}', end='')

try:
    if 'doctest' not in args:
        print('', f'index: {RESULT}', f'assert {RESULT!r}.stat().st_size', end='')
        assert open_result.stat().st_size, f'non-empty {open_result}'
        if open_result:
            print('', f'webbrowser.open({open_result!r})', end='')
            webbrowser.open(open_result)
finally:
    sys.exit(returncode)
Exemplo n.º 19
0
import subprocess
import sys

from sphinx.cmd.build import main

sys.exit(main(sys.argv[1:]))
Exemplo n.º 20
0
    input = os.environ.get("INPUT_DOCS", 'docs')
    output = os.environ.get("INPUT_DEST", 'build')

    if os.path.exists(os.path.join(input, "requirements.txt")):
        import pip
        pip.main(['install', "-r", os.path.join(input, "requirements.txt")])


    logfile = os.path.join(tempfile.gettempdir(), "sphinx-log")
    if os.path.exists(logfile):
        os.unlink(logfile)

    options = f'--keep-going --no-color -a -q -w {logfile} {input} {output}'

    main(options.split(" "))

    with open(logfile) as logs:
        loglines = logs.readlines()
        for i, line in enumerate(loglines):
            if "WARNING" in line:
                location, message = line.split("WARNING:")
                logging.debug(f"{i}: {location} - {message}")

                try:
                    file_name, line_number = extract_line_information(location)
                except ValueError as e:
                    logging.debug(e)
                    continue

                # If this isn't the last line and the next line isn't a warning,
Exemplo n.º 21
0
    elif projectTitle == path and projectREADME != '':
        _readMeTitle = ''
        _readMeText = projectREADME

    else:
        _readMeTitle = ''
        _readMeText = '\n\nStick a README.md file in the project folder to add text here.\n\n\n'

    projectREADME = m2r.convert('\n'.join(
        [_readMeTitle, '\n'.join(badges), _readMeText]))

    with open(indexPath, 'w') as o:
        o.write(projectREADME)
        o.write(defaultIndex)

    shutil.rmtree(os.path.join(out, 'source', '_static'))
    shutil.copytree(os.path.join(sphinxResource, 'sphinxStatic'),
                    os.path.join(out, 'source', '_static'))

    project.buildProject(out)

    with open(os.path.join(out, 'source', 'code', '_sasTests.md'), 'w') as o:
        o.write(SASTestMD)

    build.main([
        '-M', 'html',
        os.path.join(out, 'source'),
        os.path.join(out, 'build')
    ])
Exemplo n.º 22
0
# -*- coding: utf-8 -*-
import re
import sys

from sphinx.cmd.build import main

if __name__ == "__main__":
    sys.argv[0] = re.sub(r"(-script\.pyw?|\.exe)?$", "", sys.argv[0])
    sys.exit(main())
Exemplo n.º 23
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    warnings.warn('sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
                  RemovedInSphinx30Warning, stacklevel=2)
    return build.main(argv)
Exemplo n.º 24
0
def main(argv=sys.argv[1:]):  # type: ignore
    # type: (List[unicode]) -> int
    warnings.warn(
        'sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
        RemovedInSphinx30Warning)
    return build.main(argv)
Exemplo n.º 25
0
# -*- coding: utf-8 -*-
"""
    sphinx.__main__
    ~~~~~~~~~~~~~~~

    The Sphinx documentation toolchain.

    :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import sys

from sphinx.cmd.build import main

sys.exit(main(sys.argv[1:]))  # type: ignore
Exemplo n.º 26
0
#!/usr/bin/env python
# Script to publish the documentation on jalapeno

from fsl.utils.run import run
import os.path as op
from sphinx.cmd.build import main

main(('doc', 'doc/html'))
target = op.expanduser("~/www/doc/mcot/core")
if op.isdir(target):
    run(f"rsync -aP doc/html/ {target}/")

Exemplo n.º 27
0
def docs(output):
    """Build documentation with Sphinx"""
    from sphinx.cmd import build
    build.main(['docs', output])
Exemplo n.º 28
0
# -*- coding: utf-8 -*-
"""
    sphinx.__main__
    ~~~~~~~~~~~~~~~

    The Sphinx documentation toolchain.

    :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import sys

from sphinx.cmd.build import main

sys.exit(main(sys.argv[1:]))
Exemplo n.º 29
0
    def createDocs(self,
                   docs_path: str = "",
                   mode: str = "build"):  # pragma: no cover
        """Dokumentation erzeugen oder erneuern.

        Parameters
        ----------
        docs_path : str, optional
            Pfad nach ui-docs. The default is "".
        mode : str, optional
            Mit rebuild komplett neu erzeugen sonst nur erneuern. The default is "build".

        Returns
        -------
        bool
            ``True`` wenn erzeugt wurde, sonst ``False``.

        """
        import sphinx.ext.apidoc as apidoc
        import sphinx.cmd.build as build

        if mode == "rebuild" and osp.isdir(docs_path):
            from shutil import rmtree
            try:
                rmtree(docs_path)
            except:
                return False

        # ohne docs_path vorlage aus helper/docs kopieren
        if not osp.isdir(docs_path) or not osp.isdir(
                osp.join(docs_path, "build")):
            # conf und _static kopieren
            from distutils.dir_util import copy_tree

            # vorlage kopieren
            #
            from_path = osp.join(osp.dirname(osp.abspath(__file__)), "helper",
                                 "sphinx")
            if not osp.isdir(docs_path):
                os.mkdir(docs_path)
                # das soll eigentlich copy_tree machen
                os.mkdir(osp.join(docs_path, "source"))
                os.mkdir(osp.join(docs_path, "source", "_ext"))
                os.mkdir(osp.join(docs_path, "source", "_static"))

            try:
                copy_tree(from_path, docs_path)
            except:
                logger.debug("ERROR copy_tree {} {}".format(
                    from_path, docs_path))
                print("ERROR copy_tree {} {}".format(from_path, docs_path))
                return False

            # original docs auch kopieren
            #
            org_docs_from_path = osp.join(self._config.get("BASE_DIR", ""),
                                          'docs')

            if osp.isdir(org_docs_from_path):
                org_docs_to = osp.join(docs_path, "source", "docs")
                try:
                    copy_tree(org_docs_from_path, org_docs_to)
                except:
                    logger.debug("ERROR copy_tree {} {}".format(
                        org_docs_from_path, docs_path))

        # es wurde nichts angelegt - Fehlermeldung ausgeben
        if not osp.isdir(docs_path):
            print("### createDocs no path", docs_path)
            return False

        # ausführungs Pfad auf docs_path ändern
        os.chdir(docs_path)

        # ---- 1. rst Dateien in source erzeugen
        api_cmd = [
            '--force',  # force
            '-osource/',  # destdir
            '../',  # module_path
            '../tests*',  # exclude_pattern tests
            '../ui*'  # weitere exclude_pattern
        ]

        apidoc.main(api_cmd)

        # ---- 2. html aus rst Dateien in build erzeugen
        #

        # get project information from main version file
        import version as v

        build_cmd = [
            'source', 'build', '-Dcopyright={}'.format(v.__copyright__),
            '-Dauthor={}'.format(v.__author__), '-Dproject={}'.format(
                self._config.get("server.webserver.title", v.__project__)),
            '-Dversion={}'.format(v.__version__),
            '-Drelease={}'.format(v.__version__)
        ]

        build.main(build_cmd)

        return True
Exemplo n.º 30
0
def main(argv=sys.argv[1:]):  # type: ignore
    # type: (List[unicode]) -> int
    warnings.warn('sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
                  RemovedInSphinx30Warning)
    return build.main(argv)
Exemplo n.º 31
0
    def run(self):

        if not _HAVE_SPHINX:
            raise RuntimeError(
                "You must install Sphinx to build or test the documentation.")

        if sys.version_info[0] >= 3:
            import doctest
            from doctest import OutputChecker as _OutputChecker

            # Match u or U (possibly followed by r or R), removing it.
            # r/R can follow u/U but not precede it. Don't match the
            # single character string 'u' or 'U'.
            _u_literal_re = re.compile(
                r"(\W|^)(?<![\'\"])[uU]([rR]?[\'\"])", re.UNICODE)
             # Match b or B (possibly followed by r or R), removing.
             # r/R can follow b/B but not precede it. Don't match the
             # single character string 'b' or 'B'.
            _b_literal_re = re.compile(
                r"(\W|^)(?<![\'\"])[bB]([rR]?[\'\"])", re.UNICODE)

            class _StringPrefixFixer(_OutputChecker):

                def check_output(self, want, got, optionflags):
                    # The docstrings are written with python 2.x in mind.
                    # To make the doctests pass in python 3 we have to
                    # strip the 'u' prefix from the expected results. The
                    # actual results won't have that prefix.
                    want = re.sub(_u_literal_re, r'\1\2', want)
                    # We also have to strip the 'b' prefix from the actual
                    # results since python 2.x expected results won't have
                    # that prefix.
                    got = re.sub(_b_literal_re, r'\1\2', got)
                    return super(
                        _StringPrefixFixer, self).check_output(
                            want, got, optionflags)

                def output_difference(self, example, got, optionflags):
                    example.want = re.sub(_u_literal_re, r'\1\2', example.want)
                    got = re.sub(_b_literal_re, r'\1\2', got)
                    return super(
                        _StringPrefixFixer, self).output_difference(
                            example, got, optionflags)

            doctest.OutputChecker = _StringPrefixFixer

        if self.test:
            path = os.path.join(
                os.path.abspath('.'), "doc", "_build", "doctest")
            mode = "doctest"
        else:
            path = os.path.join(
                os.path.abspath('.'), "doc", "_build", version)
            mode = "html"

            try:
                os.makedirs(path)
            except:
                pass

        sphinx_args = ["-E", "-b", mode, "doc", path]

        # sphinx.main calls sys.exit when sphinx.build_main exists.
        # Call build_main directly so we can check status and print
        # the full path to the built docs.
        if hasattr(sphinx, 'build_main'):
            status = sphinx.build_main(sphinx_args)
        else:
            status = sphinx.main(sphinx_args)

        if status:
            raise RuntimeError("documentation step '%s' failed" % (mode,))

        sys.stdout.write("\nDocumentation step '%s' performed, results here:\n"
                         "   %s/\n" % (mode, path))
Exemplo n.º 32
0
# -*- coding: utf-8 -*-
"""
    sphinx.__main__
    ~~~~~~~~~~~~~~~

    The Sphinx documentation toolchain.

    :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import sys

from sphinx.cmd.build import main

sys.exit(main(sys.argv[1:]))  # type: ignore
Exemplo n.º 33
0
if __name__ == "__main__":
    import sys

    try:
        import sphinx
    except ImportError:
        raise NameError("Cannot find sphinx in selected interpreter.")

    version = sphinx.version_info
    if version[0] >= 1 and version[1] >= 7:
        from sphinx.cmd import build
        build.main(sys.argv[1:])
    else:
        from sphinx import cmdline
        cmdline.main(sys.argv)
Exemplo n.º 34
0
def sphinxecutor(newRst: dict) -> None:
    try:
        shutil.rmtree(f'{homeDir}sphinx-doc/build')
        shutil.rmtree(f'{homeDir}sphinx-doc/temp')
    except:
        pass

    try:
        create_dirs(
            [f'{homeDir}sphinx-doc/build', f'{homeDir}sphinx-doc/temp'])
    except:
        pass

    exporters = ""
    pickers = ""
    for owner in newRst:
        if newRst[owner]['type'] == 'exporter':
            root = f"exporter_{owner}_"
            for rst in newRst[owner]['rst'].values():
                exporters += f"{root}{rst['file'].replace('.rst', '')}\n   "

        elif newRst[owner]['type'] == 'picker':
            root = f"picker_{owner}_"
            for rst in newRst[owner]['rst'].values():
                pickers += f"{root}{rst['file'].replace('.rst', '')}\n   "

    for owner in newRst:
        if owner == 'lootnika':
            owner1 = kind = ''
        else:
            owner1 = f"{owner}_"
            kind = f"{newRst[owner]['type']}_"
        for path, rst in newRst[owner]['rst'].items():
            dst = f"{homeDir}sphinx-doc/temp/{kind}{owner1}{rst['file']}"
            shutil.copyfile(f"{homeDir}{path}", dst)

            if owner == 'lootnika':
                with open(dst, encoding='utf-8', mode='r+') as f:
                    cnt = f.read()
                    f.seek(0)
                    if '{{ exporters }}' in cnt:
                        cnt = cnt.replace('{{ exporters }}', exporters)
                        f.write(cnt)
                    if '{{ pickers }}' in cnt:
                        cnt = cnt.replace('{{ pickers }}', pickers)
                        f.write(cnt)

    shutil.copyfile(f"{homeDir}sphinx-doc/conf.py",
                    f"{homeDir}sphinx-doc/temp/conf.py")

    sys.argv.append('-M')
    sys.argv.append('html')
    sys.argv.append(f'{homeDir}sphinx-doc/temp/')
    sys.argv.append(f'{homeDir}sphinx-doc/build/')

    from sphinx.cmd import build
    build.main(sys.argv[1:])

    try:
        shutil.rmtree(f'{homeDir}webui/help/html')
    except:
        pass

    shutil.move(f'{homeDir}sphinx-doc/build/html', f'{homeDir}webui/help/')
Exemplo n.º 35
0
        event = getattr(events, name)
        title = name
        docstr = inspect.getdoc(event)
        if docstr.startswith(name):
            # Assume the first line is a signature
            title, docstr = docstr.split("\n", 1)
            docstr = docstr.strip()
        under = "." * (len(title) + 4)
        s += sec.format(low=name.lower(), title=title, under=under, docstr=docstr)
    s = s[:-9]
    fname = os.path.join(os.path.dirname(__file__), "eventsbody")
    with open(fname, "w") as f:
        f.write(s)


make_events()


def setup(app: Sphinx):
    from xonsh.pyghooks import XonshConsoleLexer

    app.add_lexer("xonshcon", XonshConsoleLexer)
    app.add_css_file("custom.css")


if __name__ == "__main__":
    # use this to debug the process from IDEs
    from sphinx.cmd import build

    build.main(["-b", "html", ".", "_build/html"])