Python sphinx.application.Sphinx() Examples

The following are 30 code examples of sphinx.application.Sphinx(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sphinx.application , or try the search function .
Example #1
Source File: __init__.py    From sphinxcontrib-programoutput with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _find_duplicate_default_nodes():
    from sphinx import addnodes # pylint:disable=import-outside-toplevel

    class App(object):

        def __init__(self):
            self.nodes = set()

        def add_node(self, node):
            self.nodes.add(node.__name__)


    app = App()
    try:
        addnodes.setup(app)
    except AttributeError:
        # Sphinx 1 doesn't have this
        pass

    return app.nodes 
Example #2
Source File: __init__.py    From cotk with Apache License 2.0 6 votes vote down vote up
def merge_autodoc_default_flags(app: Sphinx, config: Config) -> None:
    """This merges the autodoc_default_flags to autodoc_default_options."""
    if not config.autodoc_default_flags:
        return

    # Note: this option will be removed in Sphinx-4.0.  But I marked this as
    # RemovedInSphinx *30* Warning because we have to emit warnings for users
    # who will be still in use with Sphinx-3.x.  So we should replace this by
    # logger.warning() on 3.0.0 release.
    warnings.warn('autodoc_default_flags is now deprecated. '
                  'Please use autodoc_default_options instead.',
                  RemovedInSphinx30Warning, stacklevel=2)

    for option in config.autodoc_default_flags:
        if isinstance(option, str):
            config.autodoc_default_options[option] = None
        else:
            logger.warning(
                __("Ignoring invalid option in autodoc_default_flags: %r"),
                option, type='autodoc'
            ) 
Example #3
Source File: type_comment.py    From cotk with Apache License 2.0 6 votes vote down vote up
def update_annotations_using_type_comments(app: Sphinx, obj: Any, bound_method: bool) -> None:
    """Update annotations info of *obj* using type_comments."""
    try:
        function = get_type_comment(obj)
        if function and hasattr(function, 'argtypes'):
            if function.argtypes != [ast.Ellipsis]:  # type: ignore
                sig = inspect.signature(obj, bound_method)
                for i, param in enumerate(sig.parameters.values()):
                    if param.name not in obj.__annotations__:
                        annotation = ast_unparse(function.argtypes[i])  # type: ignore
                        obj.__annotations__[param.name] = annotation

            if 'return' not in obj.__annotations__:
                obj.__annotations__['return'] = ast_unparse(function.returns)  # type: ignore
    except NotImplementedError as exc:  # failed to ast.unparse()
        logger.warning("Failed to parse type_comment for %r: %s", obj, exc) 
Example #4
Source File: typehints.py    From cotk with Apache License 2.0 6 votes vote down vote up
def merge_typehints(app: Sphinx, domain: str, objtype: str, contentnode: Element) -> None:
    if domain != 'py':
        return
    if app._autodoc_typehints_description is False:  # type: ignore
        return

    signature = cast(addnodes.desc_signature, contentnode.parent[0])
    if signature['module']:
        fullname = '.'.join([signature['module'], signature['fullname']])
    else:
        fullname = signature['fullname']
    annotations = app.env.temp_data.get('annotations', {})
    if annotations.get(fullname, {}):
        field_lists = [n for n in contentnode if isinstance(n, nodes.field_list)]
        if field_lists == []:
            field_list = insert_field_list(contentnode)
            field_lists.append(field_list)

        for field_list in field_lists:
            modify_field_list(field_list, annotations[fullname]) 
Example #5
Source File: scm_tag_titles_ext.py    From cheroot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setup(app: Sphinx) -> None:
    """Initialize the extension."""
    app.add_config_value(
        'scm_version_title_settings',
        {
            'scm': 'git',
            'date_format': '%d %b %Y',
        },
        'html',
    )
    app.add_node(
        version_subtitle,
        html=(
            _visit_version_subtitle,
            _depart_version_subtitle,
        ),
    )
    app.add_directive(
        'scm-version-title', SCMVersionTitle,
    )

    return {
        'parallel_read_safe': True,
        'version': __version__,
    } 
Example #6
Source File: core.py    From pySINDy with MIT License 6 votes vote down vote up
def build(self):
        """Build the documentation. Places the data into the `outdir`
        directory. Use it like this::

            support = WebSupport(srcdir, builddir, search='xapian')
            support.build()

        This will read reStructured text files from `srcdir`. Then it will
        build the pickles and search index, placing them into `builddir`.
        It will also save node data to the database.
        """
        if not self.srcdir:
            raise RuntimeError('No srcdir associated with WebSupport object')

        from sphinx.application import Sphinx
        app = Sphinx(self.srcdir, self.srcdir, self.outdir, self.doctreedir,
                     self.buildername, self.confoverrides, status=self.status,
                     warning=self.warning)
        app.builder.set_webinfo(self.staticdir, self.staticroot,  # type: ignore
                                self.search, self.storage)

        self.storage.pre_build()
        app.build()
        self.storage.post_build() 
Example #7
Source File: conftest.py    From sphinx-gallery with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sphinx_app_wrapper(tmpdir, conf_file, req_mpl, req_pil):
    _fixturedir = os.path.join(os.path.dirname(__file__), 'testconfs')
    srcdir = os.path.join(str(tmpdir), "config_test")
    shutil.copytree(_fixturedir, srcdir)
    shutil.copytree(os.path.join(_fixturedir, "src"),
                    os.path.join(str(tmpdir), "examples"))

    base_config = """
import os
import sphinx_gallery
extensions = %r
exclude_patterns = ['_build']
source_suffix = '.rst'
master_doc = 'index'
# General information about the project.
project = u'Sphinx-Gallery <Tests>'\n\n
""" % (conf_file['extensions'],)
    with open(os.path.join(srcdir, "conf.py"), "w") as conffile:
        conffile.write(base_config + conf_file['content'])

    return SphinxAppWrapper(
        srcdir, srcdir, os.path.join(srcdir, "_build"),
        os.path.join(srcdir, "_build", "toctree"), "html", warning=StringIO(),
        status=StringIO()) 
Example #8
Source File: test_sphinx.py    From recommonmark with MIT License 6 votes vote down vote up
def sphinx_built_file(test_dir, test_file):
    os.chdir('tests/{0}'.format(test_dir))
    try:
        app = Sphinx(
            srcdir='.',
            confdir='.',
            outdir='_build/text',
            doctreedir='_build/.doctrees',
            buildername='html',
            verbosity=1,
        )
        app.build(force_all=True)
        with io.open(test_file, encoding='utf-8') as fin:
            yield fin.read().strip()
    finally:
        shutil.rmtree('_build')
        os.chdir('../..') 
Example #9
Source File: test_full.py    From sphinx-gallery with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sphinx_app(tmpdir_factory, req_mpl, req_pil):
    temp_dir = (tmpdir_factory.getbasetemp() / 'root').strpath
    src_dir = op.join(op.dirname(__file__), 'tinybuild')

    def ignore(src, names):
        return ('_build', 'gen_modules', 'auto_examples')

    shutil.copytree(src_dir, temp_dir, ignore=ignore)
    # For testing iteration, you can get similar behavior just doing `make`
    # inside the tinybuild directory
    src_dir = temp_dir
    conf_dir = temp_dir
    out_dir = op.join(temp_dir, '_build', 'html')
    toctrees_dir = op.join(temp_dir, '_build', 'toctrees')
    # Avoid warnings about re-registration, see:
    # https://github.com/sphinx-doc/sphinx/issues/5038
    with docutils_namespace():
        app = Sphinx(src_dir, conf_dir, out_dir, toctrees_dir,
                     buildername='html', status=StringIO(),
                     warning=StringIO())
        # need to build within the context manager
        # for automodule and backrefs to work
        app.build(False, [])
    return app 
Example #10
Source File: __init__.py    From sphinxcontrib-programoutput with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def app(self):
        """
        Sphinx application for the current test.
        """
        srcdir = self.srcdir
        outdir = self.outdir
        doctreedir = self.doctreedir
        confoverrides = self.confoverrides
        warningiserror = not self.ignore_warnings

        app = Sphinx(str(srcdir), str(srcdir), str(outdir), str(doctreedir), 'html',
                     status=None, warning=None, freshenv=None,
                     warningiserror=warningiserror, confoverrides=confoverrides)
        if self.build_app:
            app.build()
        return app 
Example #11
Source File: test_identifier.py    From sphinxcontrib-disqus with MIT License 6 votes vote down vote up
def test(monkeypatch, tmpdir, expected, rst_title, option):
    """Test valid and invalid values."""
    tmpdir.join('conf.py').write(BASE_CONFIG.format(py.path.local(__file__).join('..', '..')))
    tmpdir.join('conf.py').write('', mode='a')
    tmpdir.join('index.rst').write('{}.. toctree::\n    :maxdepth: 2\n.. disqus::\n{}'.format(rst_title, option))
    monkeypatch.setattr(directives, '_directives', getattr(directives, '_directives').copy())
    monkeypatch.setattr(roles, '_roles', getattr(roles, '_roles').copy())

    srcdir = confdir = str(tmpdir)
    outdir = tmpdir.join('_build', 'html')
    doctreedir = outdir.join('doctrees').ensure(dir=True, rec=True)
    app = application.Sphinx(srcdir, confdir, str(outdir), str(doctreedir), 'html')

    if expected:
        app.builder.build_all()
        html_body = outdir.join('index.html').read()
        disqus_div = re.findall(r'(<div[^>]+ id="disqus_thread"[^>]*></div>)', html_body)[0]
        assert 'data-disqus-identifier="{}"'.format(expected) in disqus_div
        return

    with pytest.raises(DisqusError) as exc:
        app.builder.build_all()
    assert 'No title nodes found in document, cannot derive disqus_identifier config value.' == exc.value.args[0] 
Example #12
Source File: test_shortname.py    From sphinxcontrib-disqus with MIT License 6 votes vote down vote up
def test(monkeypatch, tmpdir, tail, expected_error):
    """Test valid and invalid values."""
    tmpdir.join('conf.py').write(BASE_CONFIG.format(py.path.local(__file__).join('..', '..')))
    tmpdir.join('conf.py').write(tail, mode='a')
    tmpdir.join('index.rst').write('====\nMain\n====\n\n.. toctree::\n    :maxdepth: 2\n.. disqus::')
    monkeypatch.setattr(directives, '_directives', getattr(directives, '_directives').copy())
    monkeypatch.setattr(roles, '_roles', getattr(roles, '_roles').copy())

    srcdir = confdir = str(tmpdir)
    outdir = tmpdir.join('_build', 'html')
    doctreedir = outdir.join('doctrees').ensure(dir=True, rec=True)
    app = application.Sphinx(srcdir, confdir, str(outdir), str(doctreedir), 'html')

    if not expected_error:
        app.builder.build_all()
        html_body = outdir.join('index.html').read()
        disqus_div = re.findall(r'(<div[^>]+ id="disqus_thread"[^>]*></div>)', html_body)[0]
        assert 'data-disqus-shortname="good"' in disqus_div
        return

    with pytest.raises(errors.ExtensionError) as exc:
        app.builder.build_all()
    assert expected_error == exc.value.args[0] 
Example #13
Source File: extended_napoleon.py    From psyplot with GNU General Public License v2.0 6 votes vote down vote up
def setup(app):
    """Sphinx extension setup function

    When the extension is loaded, Sphinx imports this module and executes
    the ``setup()`` function, which in turn notifies Sphinx of everything
    the extension offers.

    Parameters
    ----------
    app : sphinx.application.Sphinx
        Application object representing the Sphinx process

    Notes
    -----
    This function uses the setup function of the :mod:`sphinx.ext.napoleon`
    module"""
    from sphinx.application import Sphinx
    if not isinstance(app, Sphinx):
        return  # probably called by tests

    app.connect('autodoc-process-docstring', process_docstring)
    return napoleon_setup(app) 
Example #14
Source File: type_comment.py    From cotk with Apache License 2.0 5 votes vote down vote up
def setup(app: Sphinx) -> Dict[str, Any]:
    app.connect('autodoc-before-process-signature', update_annotations_using_type_comments)

    return {'version': sphinx.__display_version__, 'parallel_read_safe': True} 
Example #15
Source File: __init__.py    From cotk with Apache License 2.0 5 votes vote down vote up
def autodoc_attrgetter(app: Sphinx, obj: Any, name: str, *defargs: Any) -> Any:
    """Alternative getattr() for types"""
    for typ, func in app.registry.autodoc_attrgettrs.items():
        if isinstance(obj, typ):
            return func(obj, name, *defargs)

    return safe_getattr(obj, name, *defargs) 
Example #16
Source File: test_functional.py    From plantuml with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def runsphinx(text, builder, confoverrides):
    f = open(os.path.join(_srcdir, 'index.rst'), 'wb')
    try:
        f.write(text.encode('utf-8'))
    finally:
        f.close()
    app = Sphinx(_srcdir, _fixturedir, _outdir, _outdir, builder,
                 confoverrides, status=sys.stdout, warning=sys.stdout)
    app.build() 
Example #17
Source File: test_sphinx.py    From recommonmark with MIT License 5 votes vote down vote up
def setUp(self):
        if self.build_path is not None:
            self.app = Sphinx(
                srcdir=self.build_path,
                confdir=self.build_path,
                outdir=os.path.join(self.build_path, '_build', 'text'),
                doctreedir=os.path.join(self.build_path, '_build', '.doctrees'),
                buildername='html',
                verbosity=1,
            )
            self.app.build(force_all=True) 
Example #18
Source File: interactive_widget.py    From idom with MIT License 5 votes vote down vote up
def setup(app: Sphinx) -> None:
    app.add_directive("interactive-widget", IteractiveWidget) 
Example #19
Source File: async_doctest.py    From idom with MIT License 5 votes vote down vote up
def setup(app: Sphinx) -> None:
    doctest_setup(app)
    app.add_builder(AsyncDoctestBuilder, override=True)
    return None 
Example #20
Source File: test_docs.py    From sharpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_html_documentation(self):
        from sphinx.application import Sphinx
        app = Sphinx(self.source_dir,
                     self.config_dir,
                     self.output_dir,
                     self.doctree_dir,
                     buildername='html',
                     warningiserror=False,
                     )
        app.build(force_all=self.all_files)
        # TODO: additional checks here if needed 
Example #21
Source File: test_docs.py    From sharpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_text_documentation(self):
        from sphinx.application import Sphinx
        # The same, but with different buildername
        app = Sphinx(self.source_dir,
                     self.config_dir,
                     self.output_dir,
                     self.doctree_dir,
                     buildername='text',
                     warningiserror=False,
                     )
        app.build(force_all=self.all_files)
        # TODO:  additional checks if needed 
Example #22
Source File: setup.py    From python-bleson with MIT License 5 votes vote down vote up
def run(self):
            from sphinx.application import Sphinx
            sph = Sphinx('./docs',  # source directory
                         './docs', # directory containing conf.py
                         './docs/_build',  # output directory
                         './docs/_build/doctrees',  # doctree directory
                         'doctest')  # finally, specify the doctest builder
            sph.build() 
Example #23
Source File: setup.py    From numdifftools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(self):
        from sphinx.application import Sphinx
        sph = Sphinx('./docs',  # source directory
                     './docs',  # directory containing conf.py
                     './docs/_build',  # output directory
                     './docs/_build/doctrees',  # doctree directory
                     'doctest')  # finally, specify the doctest builder
        sph.build() 
Example #24
Source File: __init__.py    From cotk with Apache License 2.0 5 votes vote down vote up
def format_name(self) -> str:
        """Format the name of *self.object*.

        This normally should be something that can be parsed by the generated
        directive, but doesn't need to be (Sphinx will display it unparsed
        then).
        """
        # normally the name doesn't contain the module (except for module
        # directives of course)
        return '.'.join(self.objpath) or self.modname 
Example #25
Source File: __init__.py    From sphinxcontrib-programoutput with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        # Avoid "WARNING: while setting up extension
        # sphinxcontrib.programoutput: directive u'program-output' is
        # already registered, it will be overridden".
        # This may only be needed for Sphinx 1.
        self.directives = directives._directives.copy()
        # Likewise for 'eq'
        self.roles = roles._roles.copy()

        # Avoid "node class 'toctree' is already registered, its visitors will be overridden"
        # By default this class has *no* `visit_` methods
        for node in self.duplicate_nodes_to_remove:
            if hasattr(nodes.GenericNodeVisitor, 'visit_' + node):
                delattr(nodes.GenericNodeVisitor, 'visit_' + node) 
Example #26
Source File: __init__.py    From cotk with Apache License 2.0 5 votes vote down vote up
def between(marker: str, what: Sequence[str] = None, keepempty: bool = False,
            exclude: bool = False) -> Callable:
    """Return a listener that either keeps, or if *exclude* is True excludes,
    lines between lines that match the *marker* regular expression.  If no line
    matches, the resulting docstring would be empty, so no change will be made
    unless *keepempty* is true.

    If *what* is a sequence of strings, only docstrings of a type in *what* will
    be processed.
    """
    marker_re = re.compile(marker)

    def process(app: Sphinx, what_: str, name: str, obj: Any, options: Any, lines: List[str]
                ) -> None:
        if what and what_ not in what:
            return
        deleted = 0
        delete = not exclude
        orig_lines = lines[:]
        for i, line in enumerate(orig_lines):
            if delete:
                lines.pop(i - deleted)
                deleted += 1
            if marker_re.match(line):
                delete = not delete
                if delete:
                    lines.pop(i - deleted)
                    deleted += 1
        if not lines and not keepempty:
            lines[:] = orig_lines
        # make sure there is a blank line at the end
        if lines and lines[-1]:
            lines.append('')
    return process


# This class is used only in ``autodoc.directive``,
# But we define this class here to keep compatibility (see #4538) 
Example #27
Source File: typehints.py    From cotk with Apache License 2.0 5 votes vote down vote up
def record_typehints(app: Sphinx, objtype: str, name: str, obj: Any,
                     options: Dict, args: str, retann: str) -> None:
    """Record type hints to env object."""
    try:
        if callable(obj):
            annotations = app.env.temp_data.setdefault('annotations', {})
            annotation = annotations.setdefault(name, OrderedDict())
            sig = inspect.signature(obj)
            for param in sig.parameters.values():
                if param.annotation is not param.empty:
                    annotation[param.name] = typing.stringify(param.annotation)
            if sig.return_annotation is not sig.empty:
                annotation['return'] = typing.stringify(sig.return_annotation)
    except TypeError:
        pass 
Example #28
Source File: __init__.py    From sphinxcontrib-programoutput with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def srcdir(self):
        """
        Generated source directory for test Sphinx application.
        """
        tmpdir = self.tmpdir
        srcdir = os.path.join(tmpdir, 'src')
        os.mkdir(srcdir)
        confpy = os.path.join(srcdir, 'conf.py')
        with open(confpy, 'w') as f:
            f.write(CONF_PY)
        index_document = os.path.join(srcdir, 'index.rst')
        with open(index_document, 'w') as f:
            f.write("""\
    .. toctree::

       content/doc""")
        content_directory = os.path.join(srcdir, 'content')
        os.mkdir(content_directory)
        content_document = os.path.join(content_directory, 'doc.rst')
        contents = self.document_content
        if not isinstance(contents, bytes):
            contents = contents.encode(self.document_encoding)

        with open(content_document, 'wb') as f:
            f.write(b"=====\n")
            f.write(b"Title\n")
            f.write(b"=====\n\n")

            f.write(contents)

        return srcdir 
Example #29
Source File: docstring.py    From cotk with Apache License 2.0 5 votes vote down vote up
def __init__(self, docstring: Union[str, List[str]], config: SphinxConfig = None,
                 app: Sphinx = None, what: str = '', name: str = '',
                 obj: Any = None, options: Any = None) -> None:
        self._directive_sections = ['.. index::']
        super().__init__(docstring, config, app, what, name, obj, options) 
Example #30
Source File: __init__.py    From cotk with Apache License 2.0 5 votes vote down vote up
def setup(app: Sphinx) -> Dict[str, Any]:
    """Sphinx extension setup function.

    When the extension is loaded, Sphinx imports this module and executes
    the ``setup()`` function, which in turn notifies Sphinx of everything
    the extension offers.

    Parameters
    ----------
    app : sphinx.application.Sphinx
        Application object representing the Sphinx process

    See Also
    --------
    `The Sphinx documentation on Extensions
    <http://sphinx-doc.org/extensions.html>`_

    `The Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_

    `The Extension API <http://sphinx-doc.org/extdev/appapi.html>`_

    """
    if not isinstance(app, Sphinx):
        # probably called by tests
        return {'version': __version__, 'parallel_read_safe': True}

    _patch_python_domain()

    app.setup_extension('autodoc') #change
    app.connect('autodoc-process-docstring', _process_docstring)
    app.connect('autodoc-skip-member', _skip_member)

    for name, (default, rebuild) in Config._config_values.items():
        app.add_config_value(name, default, rebuild)
    return {'version': __version__, 'parallel_read_safe': True}