Merge branch 'master' into move_cmdline_to_cmd.build

This commit is contained in:
Takeshi KOMIYA 2018-02-24 02:17:23 +09:00
commit b2b500dda5
277 changed files with 1642 additions and 827 deletions

10
.codecov.yml Normal file
View File

@ -0,0 +1,10 @@
coverage:
status:
project:
default:
# allowed to drop X% and still result in a "success" commit status
threshold: 0.05
patch:
default:
# allowed to drop X% and still result in a "success" commit status
threshold: 0.05

45
CHANGES
View File

@ -25,6 +25,9 @@ Deprecated
``sphinx.util.import_object()`` instead.
* Drop function based directive support. For now, Sphinx only supports class
based directives.
* ``Sphinx.add_source_parser()`` has changed; the *suffix* argument has
been deprecated. Please use ``Sphinx.add_source_suffix()`` instead.
* ``sphinx.util.docutils.directive_helper()`` is deprecated.
* ``sphinx.cmdline`` is deprecated. Please use ``sphinx.cmd.build`` instead.
Features added
@ -43,7 +46,7 @@ Bugs fixed
Testing
--------
Release 1.7.1 (in development)
Release 1.7.2 (in development)
==============================
Dependencies
@ -64,6 +67,44 @@ Bugs fixed
Testing
--------
Release 1.7.1 (released Feb 23, 2018)
=====================================
Deprecated
----------
* #4623: ``sphinx.build_main()`` is deprecated. Use
``sphinx.cmd.build.build_main()`` instead.
* autosummary: The interface of ``sphinx.ext.autosummary.get_documenter()`` has
been changed (Since 1.7.0)
* #4664: ``sphinx.ext.intersphinx.debug()`` is deprecated. Use
``sphinx.ext.intersphinx.inspect_main()`` instead.
Bugs fixed
----------
* #4608: epub: Invalid meta tag is generated
* #4260: autodoc: keyword only argument separator is not disappeared if it is
appeared at top of the argument list
* #4622: epub: :confval:`epub_scheme` does not effect to content.opf
* #4627: graphviz: Fit graphviz images to page
* #4617: quickstart: PROJECT_DIR argument is required
* #4623: sphinx.build_main no longer exists in 1.7.0
* #4615: The argument of ``sphinx.build`` has been changed in 1.7.0
* autosummary: The interface of ``sphinx.ext.autosummary.get_documenter()`` has
been changed
* #4630: Have order on msgids in sphinx.pot deterministic
* #4563: autosummary: Incorrect end of line punctuation detection
* #4577: Enumerated sublists with explicit start with wrong number
* #4641: A external link in TOC cannot contain "?" with ``:glob:`` option
* C++, add missing parsing of explicit casts and typeid in expression parsing.
* C++, add missing parsing of ``this`` in expression parsing.
* #4655: Fix incomplete localization strings in Polish
* #4653: Fix error reporting for parameterless ImportErrors
* #4664: Reading objects.inv fails again
* #4662: ``any`` refs with ``term`` targets crash when an ambiguity is
encountered
Release 1.7.0 (released Feb 12, 2018)
=====================================
@ -175,6 +216,8 @@ Features added
* #4271: sphinx-build supports an option called ``-j auto`` to adjust numbers of
processes automatically.
* Napoleon: added option to specify custom section tags.
Features removed
----------------

View File

@ -81,6 +81,15 @@ Documentation is available from `sphinx-doc.org`__.
__ http://www.sphinx-doc.org/
Get in touch
============
- Report bugs, suggest features or view the source code `on GitHub`_.
- For less well defined questions or ideas, use the `mailing list`_.
.. _on GitHub: https://github.com/sphinx-doc/sphinx
.. _mailing list: https://groups.google.com/forum/#!forum/sphinx-users
Testing
=======

View File

@ -1219,16 +1219,21 @@ that use Sphinx's HTMLWriter class.
.. versionadded:: 1.3
.. confval:: htmlhelp_basename
Output file base name for HTML help builder. Default is ``'pydoc'``.
.. confval:: html_experimental_html5_writer
Output is processed with HTML5 writer. This feature needs docutils 0.13 or newer. Default is ``False``.
.. versionadded:: 1.6
.. _htmlhelp-options:
Options for HTML help output
-----------------------------
.. confval:: htmlhelp_basename
Output file base name for HTML help builder. Default is ``'pydoc'``.
.. _applehelp-options:
Options for Apple Help output

View File

@ -398,7 +398,7 @@ There are also new config values that you can set:
.. confval:: autodoc_inherit_docstrings
This value controls the docstrings inheritance.
If set to True the cocstring for classes or methods, if not explicitly set,
If set to True the docstring for classes or methods, if not explicitly set,
is inherited form parents.
The default is ``True``.

View File

@ -85,7 +85,9 @@ package.
.. automethod:: Sphinx.add_search_language(cls)
.. automethod:: Sphinx.add_source_parser(suffix, parser)
.. automethod:: Sphinx.add_source_suffix(suffix, filetype)
.. automethod:: Sphinx.add_source_parser(parser)
.. automethod:: Sphinx.add_env_collector(collector)

View File

@ -3,6 +3,35 @@
Parser API
==========
`The docutils documentation describes`__ parsers as follows:
The Parser analyzes the input document and creates a node tree
representation.
__ http://docutils.sourceforge.net/docs/dev/hacking.html#parsing-the-document
In Sphinx, the parser modules works as same as docutils. The parsers are
registered to Sphinx by extensions using Application APIs;
:meth:`Sphinx.add_source_suffix()` and :meth:`Sphinx.add_source_parsers()`.
The *source suffix* is a mapping from file suffix to file type. For example,
``.rst`` file is mapped to ``'restructuredtext'`` type. Sphinx uses the
file type to looking for parsers from registered list. On searching,
Sphinx refers to the ``Parser.supported`` attribute and picks up a parser
which contains the file type in the attribute.
The users can override the source suffix mappings using
:confval:`source_suffix` like following::
# a mapping from file suffix to file types
source_suffix = {
'.rst': 'restructuredtext',
'.md': 'markdown',
}
You should indicate file types your parser supports. This will allow users
to configure their settings appropriately.
.. module:: sphinx.parsers
.. autoclass:: Parser

View File

@ -70,8 +70,8 @@ By prefixing the name of the overridden template with an exclamation mark,
Sphinx will load the layout template from the underlying HTML theme.
**Important**: If you override a block, call ``{{ super() }}`` somewhere to
render the block's content in the extended template -- unless you don't want
that content to show up.
render the block's original content in the extended template -- unless you
don't want that content to show up.
Working with the builtin templates

View File

@ -15,6 +15,7 @@
from __future__ import absolute_import
import os
import sys
import warnings
from os import path
@ -23,6 +24,7 @@ from .deprecation import RemovedInSphinx20Warning
if False:
# For type annotation
# note: Don't use typing.TYPE_CHECK here (for py27 and py34).
from typing import Any # NOQA
@ -71,20 +73,43 @@ if __version__.endswith('+'):
def main(*args, **kwargs):
# type: (Any, Any) -> int
from .cmd import build
warnings.warn(
'`sphinx.main()` has moved to `sphinx.cmd.build.main()`.',
RemovedInSphinx20Warning,
stacklevel=2,
)
from .cmd import build
args = args[1:] # skip first argument to adjust arguments (refs: #4615)
return build.main(*args, **kwargs)
def build_main(argv=sys.argv):
"""Sphinx build "main" command-line entry."""
from .cmd import build
warnings.warn(
'`sphinx.build_main()` has moved to `sphinx.cmd.build.build_main()`.',
RemovedInSphinx20Warning,
stacklevel=2,
)
return build.build_main(argv[1:]) # skip first argument to adjust arguments (refs: #4615)
def make_main(argv=sys.argv):
"""Sphinx build "make mode" entry."""
from .cmd import build
warnings.warn(
'`sphinx.build_main()` has moved to `sphinx.cmd.build.make_main()`.',
RemovedInSphinx20Warning,
stacklevel=2,
)
return build.make_main(argv[1:]) # skip first argument to adjust arguments (refs: #4615)
if __name__ == '__main__':
from .cmd import build
warnings.warn(
'`sphinx` has moved to `sphinx.build`.',
RemovedInSphinx20Warning,
stacklevel=2,
)
from .cmd import build
build.main()

View File

@ -9,10 +9,11 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
if False:
# For type annotation
if TYPE_CHECKING:
from typing import List, Sequence # NOQA

View File

@ -10,13 +10,12 @@
"""
import warnings
from typing import TYPE_CHECKING
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.ext.apidoc import main as _main
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any # NOQA
from sphinx.application import Sphinx # NOQA
@ -28,6 +27,7 @@ def main(*args, **kwargs):
RemovedInSphinx20Warning,
stacklevel=2,
)
args = args[1:] # skip first argument to adjust arguments (refs: #4615)
_main(*args, **kwargs)

View File

@ -19,10 +19,10 @@ import warnings
from collections import deque
from inspect import isclass
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives, roles
from six import iteritems, itervalues
from six import itervalues
from six.moves import cStringIO
import sphinx
@ -36,18 +36,20 @@ from sphinx.errors import (
from sphinx.events import EventManager
from sphinx.locale import __
from sphinx.registry import SphinxComponentRegistry
from sphinx.util import docutils
from sphinx.util import import_object
from sphinx.util import logging
from sphinx.util import pycompat # noqa: F401
from sphinx.util.build_phase import BuildPhase
from sphinx.util.console import bold # type: ignore
from sphinx.util.docutils import is_html5_writer_available, directive_helper
from sphinx.util.docutils import directive_helper
from sphinx.util.i18n import find_catalog_source_files
from sphinx.util.osutil import abspath, ensuredir
from sphinx.util.tags import Tags
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Tuple, Type, Union # NOQA
from docutils import nodes # NOQA
from docutils.parsers import Parser # NOQA
from docutils.transform import Transform # NOQA
from sphinx.builders import Builder # NOQA
@ -56,7 +58,7 @@ if False:
from sphinx.extension import Extension # NOQA
from sphinx.roles import XRefRole # NOQA
from sphinx.theming import Theme # NOQA
from sphinx.util.typing import RoleFunction # NOQA
from sphinx.util.typing import RoleFunction, TitleGetter # NOQA
builtin_extensions = (
'sphinx.builders.applehelp',
@ -126,19 +128,19 @@ class Sphinx(object):
freshenv=False, warningiserror=False, tags=None, verbosity=0,
parallel=0):
# type: (unicode, unicode, unicode, unicode, unicode, Dict, IO, IO, bool, bool, List[unicode], int, int) -> None # NOQA
self.phase = BuildPhase.INITIALIZATION
self.verbosity = verbosity
self.extensions = {} # type: Dict[unicode, Extension]
self._setting_up_extension = ['?'] # type: List[unicode]
self.builder = None # type: Builder
self.env = None # type: BuildEnvironment
self.registry = SphinxComponentRegistry()
self.enumerable_nodes = {} # type: Dict[nodes.Node, Tuple[unicode, Callable]] # NOQA
self.html_themes = {} # type: Dict[unicode, unicode]
# validate provided directories
self.srcdir = abspath(srcdir)
self.outdir = abspath(outdir)
self.doctreedir = abspath(doctreedir)
self.srcdir = abspath(srcdir) # type: unicode
self.outdir = abspath(outdir) # type: unicode
self.doctreedir = abspath(doctreedir) # type: unicode
self.confdir = confdir
if self.confdir: # confdir is optional
self.confdir = abspath(self.confdir)
@ -252,8 +254,6 @@ class Sphinx(object):
self._init_env(freshenv)
# set up the builder
self._init_builder()
# set up the enumerable nodes
self._init_enumerable_nodes()
def _init_i18n(self):
# type: () -> None
@ -323,15 +323,11 @@ class Sphinx(object):
self.builder.init()
self.emit('builder-inited')
def _init_enumerable_nodes(self):
# type: () -> None
for node, settings in iteritems(self.enumerable_nodes):
self.env.get_domain('std').enumerable_nodes[node] = settings # type: ignore
# ---- main "build" method -------------------------------------------------
def build(self, force_all=False, filenames=None):
# type: (bool, List[unicode]) -> None
self.phase = BuildPhase.READING
try:
if force_all:
self.builder.compile_all_catalogs()
@ -619,49 +615,16 @@ class Sphinx(object):
Added the support for keyword arguments giving visit functions.
"""
logger.debug('[app] adding node: %r', (node, kwds))
if not kwds.pop('override', False) and \
hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__):
if not kwds.pop('override', False) and docutils.is_node_registered(node):
logger.warning(__('while setting up extension %s: node class %r is '
'already registered, its visitors will be overridden'),
self._setting_up_extension, node.__name__,
type='app', subtype='add_node')
nodes._add_node_class_names([node.__name__])
for key, val in iteritems(kwds):
try:
visit, depart = val
except ValueError:
raise ExtensionError(__('Value for key %r must be a '
'(visit, depart) function tuple') % key)
translator = self.registry.translators.get(key)
translators = []
if translator is not None:
translators.append(translator)
elif key == 'html':
from sphinx.writers.html import HTMLTranslator
translators.append(HTMLTranslator)
if is_html5_writer_available():
from sphinx.writers.html5 import HTML5Translator
translators.append(HTML5Translator)
elif key == 'latex':
from sphinx.writers.latex import LaTeXTranslator
translators.append(LaTeXTranslator)
elif key == 'text':
from sphinx.writers.text import TextTranslator
translators.append(TextTranslator)
elif key == 'man':
from sphinx.writers.manpage import ManualPageTranslator
translators.append(ManualPageTranslator)
elif key == 'texinfo':
from sphinx.writers.texinfo import TexinfoTranslator
translators.append(TexinfoTranslator)
for translator in translators:
setattr(translator, 'visit_' + node.__name__, visit)
if depart:
setattr(translator, 'depart_' + node.__name__, depart)
docutils.register_node(node)
self.registry.add_translation_handlers(node, **kwds)
def add_enumerable_node(self, node, figtype, title_getter=None, **kwds):
# type: (nodes.Node, unicode, Callable, Any) -> None
# type: (nodes.Node, unicode, TitleGetter, Any) -> None
"""Register a Docutils node class as a numfig target.
Sphinx numbers the node automatically. And then the users can refer it
@ -685,9 +648,17 @@ class Sphinx(object):
.. versionadded:: 1.4
"""
self.enumerable_nodes[node] = (figtype, title_getter)
self.registry.add_enumerable_node(node, figtype, title_getter)
self.add_node(node, **kwds)
@property
def enumerable_nodes(self):
# type: () -> Dict[nodes.Node, Tuple[unicode, TitleGetter]]
warnings.warn('app.enumerable_nodes() is deprecated. '
'Use app.get_domain("std").enumerable_nodes instead.',
RemovedInSphinx30Warning)
return self.registry.enumerable_nodes
def add_directive(self, name, obj, content=None, arguments=None, **options):
# type: (unicode, Any, bool, Tuple[int, int, bool], Any) -> None
"""Register a Docutils directive.
@ -735,13 +706,12 @@ class Sphinx(object):
'already registered, it will be overridden'),
self._setting_up_extension[-1], name,
type='app', subtype='add_directive')
directive = directive_helper(obj, content, arguments, **options)
directives.register_directive(name, directive)
if not isclass(obj) or not issubclass(obj, Directive):
warnings.warn('function based directive support is now deprecated. '
'Use class based directive instead.',
RemovedInSphinx30Warning)
directive = directive_helper(obj, content, arguments, **options)
directives.register_directive(name, directive)
else:
directives.register_directive(name, obj)
def add_role(self, name, role):
# type: (unicode, Any) -> None
@ -1032,9 +1002,7 @@ class Sphinx(object):
.. versionadded:: 1.3
"""
logger.debug('[app] adding latex package: %r', packagename)
if hasattr(self.builder, 'usepackages'): # only for LaTeX builder
self.builder.usepackages.append((packagename, options)) # type: ignore
self.registry.add_latex_package(packagename, options)
def add_lexer(self, alias, lexer):
# type: (unicode, Any) -> None
@ -1102,13 +1070,25 @@ class Sphinx(object):
assert issubclass(cls, SearchLanguage)
languages[cls.lang] = cls
def add_source_parser(self, suffix, parser):
# type: (unicode, Parser) -> None
"""Register a parser class for specified *suffix*.
def add_source_suffix(self, suffix, filetype):
# type: (unicode, unicode) -> None
"""Register a suffix of source files.
Same as :confval:`source_suffix`. The users can override this
using the setting.
"""
self.registry.add_source_suffix(suffix, filetype)
def add_source_parser(self, *args):
# type: (Any) -> None
"""Register a parser class.
.. versionadded:: 1.4
.. versionchanged:: 1.8
*suffix* argument is deprecated. It only accepts *parser* argument.
Use :meth:`add_source_suffix` API to register suffix instead.
"""
self.registry.add_source_parser(suffix, parser)
self.registry.add_source_parser(*args)
def add_env_collector(self, collector):
# type: (Type[EnvironmentCollector]) -> None

View File

@ -11,12 +11,14 @@
import warnings
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.environment.adapters.asset import ImageAdapter
from sphinx.util import i18n, import_object, logging, status_iterator
from sphinx.util.build_phase import BuildPhase
from sphinx.util.console import bold # type: ignore
from sphinx.util.i18n import find_catalog
from sphinx.util.osutil import SEP, ensuredir, relative_uri
@ -32,8 +34,7 @@ try:
except ImportError:
multiprocessing = None
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA
@ -127,9 +128,7 @@ class Builder(object):
This method returns an instance of ``default_translator_class`` by default.
Users can replace the translator class with ``app.set_translator()`` API.
"""
translator_class = self.app.registry.get_translator_class(self)
assert translator_class, "translator not found for %s" % self.__class__.__name__
return translator_class(*args)
return self.app.registry.create_translator(self, *args)
@property
def translator_class(self):
@ -365,6 +364,7 @@ class Builder(object):
logger.info('done')
# global actions
self.app.phase = BuildPhase.CONSISTENCY_CHECK
logger.info(bold('checking consistency... '), nonl=True)
self.env.check_consistency()
logger.info('done')
@ -373,6 +373,8 @@ class Builder(object):
logger.info(bold('no targets are out of date.'))
return
self.app.phase = BuildPhase.RESOLVING
# filter "docnames" (list of outdated files) by the updated
# found_docs of the environment; this will remove docs that
# have since been removed
@ -437,7 +439,9 @@ class Builder(object):
with logging.pending_warnings():
for docname in status_iterator(docnames, 'writing output... ', "darkgreen",
len(docnames), self.app.verbosity):
self.app.phase = BuildPhase.RESOLVING
doctree = self.env.get_and_resolve_doctree(docname, self)
self.app.phase = BuildPhase.WRITING
self.write_doc_serialized(docname, doctree)
self.write_doc(docname, doctree)
@ -445,18 +449,22 @@ class Builder(object):
# type: (Sequence[unicode], int) -> None
def write_process(docs):
# type: (List[Tuple[unicode, nodes.Node]]) -> None
self.app.phase = BuildPhase.WRITING
for docname, doctree in docs:
self.write_doc(docname, doctree)
# warm up caches/compile templates using the first document
firstname, docnames = docnames[0], docnames[1:]
self.app.phase = BuildPhase.RESOLVING
doctree = self.env.get_and_resolve_doctree(firstname, self)
self.app.phase = BuildPhase.WRITING
self.write_doc_serialized(firstname, doctree)
self.write_doc(firstname, doctree)
tasks = ParallelTasks(nproc)
chunks = make_chunks(docnames, nproc)
self.app.phase = BuildPhase.RESOLVING
for chunk in status_iterator(chunks, 'writing output... ', "darkgreen",
len(chunks), self.app.verbosity):
arg = []

View File

@ -13,6 +13,7 @@ import os
import re
from collections import namedtuple
from os import path
from typing import TYPE_CHECKING
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
from docutils import nodes
@ -34,8 +35,7 @@ except ImportError:
except ImportError:
Image = None
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -16,6 +16,7 @@ import plistlib
import shlex
import subprocess
from os import path, environ
from typing import TYPE_CHECKING
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.config import string_classes
@ -27,8 +28,7 @@ from sphinx.util.matching import Matcher
from sphinx.util.osutil import copyfile, ensuredir, make_filename
from sphinx.util.pycompat import htmlescape
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -11,6 +11,7 @@
import codecs
from os import path
from typing import TYPE_CHECKING
from six import iteritems
@ -24,8 +25,7 @@ from sphinx.util.fileutil import copy_asset_file
from sphinx.util.osutil import ensuredir, os_path
from sphinx.util.pycompat import htmlescape
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -15,6 +15,7 @@ from __future__ import absolute_import
import gzip
import re
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
@ -29,8 +30,7 @@ try:
except ImportError:
import lxml.etree as etree # type: ignore
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -9,11 +9,11 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from sphinx.builders import Builder
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Set # NOQA
from docutils import nodes # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -12,6 +12,7 @@
from collections import namedtuple
from os import path
from typing import TYPE_CHECKING
from sphinx import package_dir
from sphinx.builders import _epub_base
@ -21,8 +22,7 @@ from sphinx.util.fileutil import copy_asset_file
from sphinx.util.i18n import format_date
from sphinx.util.osutil import make_filename
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Iterable, List # NOQA
from docutils import nodes # NOQA
from sphinx.application import Sphinx # NOQA
@ -134,6 +134,7 @@ class Epub3Builder(_epub_base.EpubBuilder):
metadata['ibook_scroll_axis'] = IBOOK_SCROLL_AXIS.get(writing_mode)
metadata['date'] = self.esc(format_date("%Y-%m-%dT%H:%M:%SZ"))
metadata['version'] = self.esc(self.config.version)
metadata['epub_version'] = self.config.epub_version
return metadata
def prepare_writing(self, docnames):
@ -144,6 +145,7 @@ class Epub3Builder(_epub_base.EpubBuilder):
self.globalcontext['theme_writing_mode'] = THEME_WRITING_MODES.get(writing_mode)
self.globalcontext['html_tag'] = self.html_tag
self.globalcontext['use_meta_charset'] = self.use_meta_charset
self.globalcontext['skip_ua_compatible'] = True
def build_navlist(self, navnodes):
# type: (List[nodes.Node]) -> List[NavPoint]
@ -229,6 +231,7 @@ def setup(app):
# config values
app.add_config_value('epub_basename', lambda self: make_filename(self.project), None)
app.add_config_value('epub_version', 3.0, 'epub') # experimental
app.add_config_value('epub_theme', 'epub', 'epub')
app.add_config_value('epub_theme_options', {}, 'epub')
app.add_config_value('epub_title', lambda self: self.html_title, 'epub')

View File

@ -12,10 +12,11 @@
from __future__ import unicode_literals
from codecs import open
from collections import defaultdict
from collections import defaultdict, OrderedDict
from datetime import datetime, tzinfo, timedelta
from os import path, walk, getenv
from time import time
from typing import TYPE_CHECKING
from uuid import uuid4
from six import iteritems, StringIO
@ -29,8 +30,7 @@ from sphinx.util.nodes import extract_messages, traverse_translatable_index
from sphinx.util.osutil import safe_relpath, ensuredir, canon_path
from sphinx.util.tags import Tags
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, DefaultDict, Dict, Iterable, List, Set, Tuple # NOQA
from docutils import nodes # NOQA
from sphinx.util.i18n import CatalogInfo # NOQA
@ -68,8 +68,8 @@ class Catalog(object):
# type: () -> None
self.messages = [] # type: List[unicode]
# retain insertion order, a la OrderedDict
self.metadata = {} # type: Dict[unicode, List[Tuple[unicode, int, unicode]]]
# msgid -> file, line, uid
self.metadata = OrderedDict() # type: Dict[unicode, List[Tuple[unicode, int, unicode]]] # NOQA
# msgid -> file, line, uid
def add(self, msg, origin):
# type: (unicode, MsgOrigin) -> None
@ -237,7 +237,8 @@ class MessageCatalogBuilder(I18nBuilder):
def _extract_from_template(self):
# type: () -> None
files = self._collect_templates()
files = list(self._collect_templates())
files.sort()
logger.info(bold('building [%s]: ' % self.name), nonl=1)
logger.info('targets for %d template files', len(files))

View File

@ -16,6 +16,7 @@ import sys
import warnings
from hashlib import md5
from os import path
from typing import TYPE_CHECKING
import docutils
from docutils import nodes
@ -51,8 +52,7 @@ from sphinx.util.osutil import SEP, os_path, relative_uri, ensuredir, \
movefile, copyfile
from sphinx.writers.html import HTMLWriter, HTMLTranslator
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, IO, Iterable, Iterator, List, Type, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA
@ -600,9 +600,9 @@ class StandaloneHTMLBuilder(Builder):
doctree.settings = self.docsettings
self.secnumbers = self.env.toc_secnumbers.get(docname, {})
self.fignumbers = self.env.toc_fignumbers.get(docname, {})
self.fignumbers = self.env.toc_fignumbers.get(docname, {}) # type: Dict[unicode, Dict[unicode, Tuple[int, ...]]] # NOQA
self.imgpath = relative_uri(self.get_target_uri(docname), '_images')
self.dlpath = relative_uri(self.get_target_uri(docname), '_downloads')
self.dlpath = relative_uri(self.get_target_uri(docname), '_downloads') # type: unicode
self.current_docname = docname
self.docwriter.write(doctree, destination)
self.docwriter.assemble_parts()

View File

@ -14,6 +14,7 @@ from __future__ import print_function
import codecs
import os
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
@ -24,8 +25,7 @@ from sphinx.util import logging
from sphinx.util.osutil import make_filename
from sphinx.util.pycompat import htmlescape
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, IO, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -11,6 +11,7 @@
import os
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.frontend import OptionParser
@ -32,8 +33,7 @@ from sphinx.util.nodes import inline_all_toctrees
from sphinx.util.osutil import SEP, make_filename
from sphinx.writers.latex import LaTeXWriter, LaTeXTranslator
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Iterable, List, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA
@ -62,7 +62,7 @@ class LaTeXBuilder(Builder):
# type: () -> None
self.docnames = [] # type: Iterable[unicode]
self.document_data = [] # type: List[Tuple[unicode, unicode, unicode, unicode, unicode, bool]] # NOQA
self.usepackages = [] # type: List[unicode]
self.usepackages = self.app.registry.latex_packages
texescape.init()
def get_outdated_docs(self):

View File

@ -14,6 +14,7 @@ import re
import socket
import threading
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
from requests.exceptions import HTTPError
@ -37,8 +38,7 @@ from sphinx.util.console import ( # type: ignore
)
from sphinx.util.requests import is_ssl_error
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Set, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.util.requests.requests import Response # NOQA

View File

@ -10,6 +10,7 @@
"""
from os import path
from typing import TYPE_CHECKING
from docutils.frontend import OptionParser
from docutils.io import FileOutput
@ -24,8 +25,7 @@ from sphinx.util.nodes import inline_all_toctrees
from sphinx.util.osutil import make_filename
from sphinx.writers.manpage import ManualPageWriter, ManualPageTranslator
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Set, Union # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -14,6 +14,7 @@ import os
import posixpath
import re
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
from six import text_type
@ -26,8 +27,7 @@ from sphinx.util import force_decode, logging
from sphinx.util.osutil import make_filename
from sphinx.util.pycompat import htmlescape
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -11,6 +11,7 @@
import os
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.frontend import OptionParser
@ -30,8 +31,7 @@ from sphinx.util.nodes import inline_all_toctrees
from sphinx.util.osutil import SEP, make_filename
from sphinx.writers.texinfo import TexinfoWriter, TexinfoTranslator
if False:
# For type annotation
if TYPE_CHECKING:
from sphinx.application import Sphinx # NOQA
from typing import Any, Dict, Iterable, List, Tuple, Union # NOQA

View File

@ -11,6 +11,7 @@
import codecs
from os import path
from typing import TYPE_CHECKING
from docutils.io import StringOutput
@ -19,8 +20,7 @@ from sphinx.util import logging
from sphinx.util.osutil import ensuredir, os_path
from sphinx.writers.text import TextWriter, TextTranslator
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Iterator, Set, Tuple # NOQA
from docutils import nodes # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -9,8 +9,9 @@
:license: BSD, see LICENSE for details.
"""
if False:
# For type annotation
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -11,6 +11,7 @@
import codecs
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.io import StringOutput
@ -21,8 +22,7 @@ from sphinx.util import logging
from sphinx.util.osutil import ensuredir, os_path
from sphinx.writers.xml import XMLWriter, PseudoXMLWriter
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Iterator, Set # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -15,6 +15,7 @@ import multiprocessing
import os
import sys
import traceback
from typing import TYPE_CHECKING
from docutils.utils import SystemMessage
from six import text_type, binary_type
@ -27,8 +28,7 @@ from sphinx.util.console import red, nocolor, color_terminal # type: ignore
from sphinx.util.docutils import docutils_namespace, patch_docutils
from sphinx.util.pycompat import terminal_safe
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, IO, List, Union # NOQA

View File

@ -19,6 +19,7 @@ import time
from collections import OrderedDict
from io import open
from os import path
from typing import TYPE_CHECKING
# try to import readline, unix specific enhancement
try:
@ -43,8 +44,7 @@ from sphinx.util.console import ( # type: ignore
from sphinx.util.osutil import ensuredir, make_filename
from sphinx.util.template import SphinxRenderer
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, List, Pattern, Union # NOQA
TERM_ENCODING = getattr(sys.stdin, 'encoding', None)
@ -533,7 +533,7 @@ Makefile to be used with sphinx-build.
parser.add_argument('--version', action='version', dest='show_version',
version='%%(prog)s %s' % __display_version__)
parser.add_argument('path', metavar='PROJECT_DIR', default='.',
parser.add_argument('path', metavar='PROJECT_DIR', default='.', nargs='?',
help='output path')
group = parser.add_argument_group('Structure options')

View File

@ -12,12 +12,12 @@ from __future__ import print_function
import sys
import warnings
from typing import TYPE_CHECKING
from sphinx.cmd import build
from sphinx.deprecation import RemovedInSphinx30Warning
if False:
# For type annotation
if TYPE_CHECKING:
import argparse # NOQA
from typing import Any, IO, List, Union # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -13,7 +13,7 @@ import re
import traceback
from collections import OrderedDict
from os import path, getenv
from typing import Any, NamedTuple, Union
from typing import TYPE_CHECKING, Any, NamedTuple, Union
from six import PY2, PY3, iteritems, string_types, binary_type, text_type, integer_types
@ -24,8 +24,7 @@ from sphinx.util.i18n import format_date
from sphinx.util.osutil import cd
from sphinx.util.pycompat import execfile_, NoneType
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Iterable, Iterator, List, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.util.tags import Tags # NOQA

View File

@ -10,6 +10,7 @@
"""
import re
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives, roles
@ -29,8 +30,7 @@ from sphinx.directives.patches import ( # noqa
Figure, Meta
)
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@ -10,6 +10,7 @@
import codecs
import sys
from difflib import unified_diff
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives
@ -21,8 +22,7 @@ from sphinx.util import logging
from sphinx.util import parselinenos
from sphinx.util.nodes import set_source_info
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA

View File

@ -7,6 +7,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from docutils.parsers.rst.directives.admonitions import BaseAdmonition
@ -21,8 +23,7 @@ from sphinx.util.matching import patfilter
from sphinx.util.nodes import explicit_title_re, set_source_info, \
process_index_entry
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
@ -72,7 +73,9 @@ class TocTree(Directive):
for entry in self.content:
if not entry:
continue
if glob and ('*' in entry or '?' in entry or '[' in entry):
# look for explicit titles ("Some Title <document>")
explicit = explicit_title_re.match(entry)
if glob and ('*' in entry or '?' in entry or '[' in entry) and not explicit:
patname = docname_join(env.docname, entry)
docnames = sorted(patfilter(all_docnames, patname))
for docname in docnames:
@ -84,11 +87,9 @@ class TocTree(Directive):
'toctree glob pattern %r didn\'t match any documents'
% entry, line=self.lineno))
else:
# look for explicit titles ("Some Title <document>")
m = explicit_title_re.match(entry)
if m:
ref = m.group(2)
title = m.group(1)
if explicit:
ref = explicit.group(2)
title = explicit.group(1)
docname = ref
else:
ref = docname = entry

View File

@ -7,6 +7,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import directives
from docutils.parsers.rst.directives import images, html, tables
@ -14,8 +16,7 @@ from docutils.parsers.rst.directives import images, html, tables
from sphinx import addnodes
from sphinx.util.nodes import set_source_info
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Dict, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -11,14 +11,14 @@
"""
import copy
from typing import TYPE_CHECKING
from six import iteritems
from sphinx.errors import SphinxError
from sphinx.locale import _
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Iterable, List, Tuple, Type, Union # NOQA
from docutils import nodes # NOQA
from docutils.parsers.rst.states import Inliner # NOQA

View File

@ -11,6 +11,7 @@
import re
import string
from typing import TYPE_CHECKING
from docutils import nodes
@ -22,8 +23,7 @@ from sphinx.roles import XRefRole
from sphinx.util.docfields import Field, TypedField
from sphinx.util.nodes import make_refnode
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Iterator, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA

View File

@ -11,6 +11,7 @@
import re
from copy import deepcopy
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives
@ -28,8 +29,7 @@ from sphinx.util.nodes import make_refnode
from sphinx.util.pycompat import UnicodeMixin
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Iterator, List, Match, Pattern, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA
@ -530,6 +530,12 @@ _expression_bin_ops = [
_expression_unary_ops = ["++", "--", "*", "&", "+", "-", "!", "~"]
_expression_assignment_ops = ["=", "*=", "/=", "%=", "+=", "-=",
">>=", "<<=", "&=", "^=", "|="]
_id_explicit_cast = {
'dynamic_cast': 'dc',
'static_cast': 'sc',
'const_cast': 'cc',
'reinterpret_cast': 'rc'
}
class NoOldIdError(UnicodeMixin, Exception):
@ -779,6 +785,17 @@ class ASTStringLiteral(ASTBase):
signode.append(nodes.Text(txt, txt))
class ASTThisLiteral(ASTBase):
def __unicode__(self):
return "this"
def get_id(self, version):
return "fpT"
def describe_signature(self, signode, mode, env, symbol):
signode.append(nodes.Text("this"))
class ASTParenExpr(ASTBase):
def __init__(self, expr):
self.expr = expr
@ -1028,6 +1045,56 @@ class ASTNoexceptExpr(ASTBase):
signode.append(nodes.Text(')'))
class ASTExplicitCast(ASTBase):
def __init__(self, cast, typ, expr):
assert cast in _id_explicit_cast
self.cast = cast
self.typ = typ
self.expr = expr
def __unicode__(self):
res = [self.cast]
res.append('<')
res.append(text_type(self.typ))
res.append('>(')
res.append(text_type(self.expr))
res.append(')')
return u''.join(res)
def get_id(self, version):
return (_id_explicit_cast[self.cast] +
self.typ.get_id(version) +
self.expr.get_id(version))
def describe_signature(self, signode, mode, env, symbol):
signode.append(nodes.Text(self.cast))
signode.append(nodes.Text('<'))
self.typ.describe_signature(signode, mode, env, symbol)
signode.append(nodes.Text('>'))
signode.append(nodes.Text('('))
self.expr.describe_signature(signode, mode, env, symbol)
signode.append(nodes.Text(')'))
class ASTTypeId(ASTBase):
def __init__(self, typeOrExpr, isType):
self.typeOrExpr = typeOrExpr
self.isType = isType
def __unicode__(self):
return 'typeid(' + text_type(self.typeOrExpr) + ')'
def get_id(self, version):
prefix = 'ti' if self.isType else 'te'
return prefix + self.typeOrExpr.get_id(version)
def describe_signature(self, signode, mode, env, symbol):
signode.append(nodes.Text('typeid'))
signode.append(nodes.Text('('))
self.typeOrExpr.describe_signature(signode, mode, env, symbol)
signode.append(nodes.Text(')'))
class ASTPostfixCallExpr(ASTBase):
def __init__(self, exprs):
self.exprs = exprs
@ -4069,7 +4136,10 @@ class DefinitionParser(object):
res = self._parse_literal()
if res is not None:
return res
# TODO: try 'this' and lambda expression
self.skip_ws()
if self.skip_word("this"):
return ASTThisLiteral()
# TODO: try lambda expression
res = self._parse_fold_or_paren_expression()
if res is not None:
return res
@ -4097,39 +4167,94 @@ class DefinitionParser(object):
# | "typeid" "(" expression ")"
# | "typeid" "(" type-id ")"
# TODO: try the productions with prefixes:
# dynamic_cast, static_cast, reinterpret_cast, const_cast, typeid
prefixType = None
pos = self.pos
try:
prefix = self._parse_primary_expression()
prefixType = 'expr'
except DefinitionError as eOuter:
self.pos = pos
prefix = None # type: Any
self.skip_ws()
cast = None
for c in _id_explicit_cast:
if self.skip_word_and_ws(c):
cast = c
break
if cast is not None:
prefixType = "cast"
if not self.skip_string("<"):
self.fail("Expected '<' afer '%s'." % cast)
typ = self._parse_type(False)
self.skip_ws()
if not self.skip_string_and_ws(">"):
self.fail("Expected '>' after type in '%s'." % cast)
if not self.skip_string("("):
self.fail("Expected '(' in '%s'." % cast)
def parser():
return self._parse_expression(inTemplate=False)
expr = self._parse_expression_fallback([')'], parser)
self.skip_ws()
if not self.skip_string(")"):
self.fail("Expected ')' to end '%s'." % cast)
prefix = ASTExplicitCast(cast, typ, expr)
elif self.skip_word_and_ws("typeid"):
prefixType = "typeid"
if not self.skip_string_and_ws('('):
self.fail("Expected '(' after 'typeid'.")
pos = self.pos
try:
# we are potentially casting, so save parens for us
# TODO: hmm, would we need to try both with operatorCast and with None?
prefix = self._parse_type(False, 'operatorCast')
prefixType = 'typeOperatorCast'
# | simple-type-specifier "(" expression-list [opt] ")"
# | simple-type-specifier braced-init-list
# | typename-specifier "(" expression-list [opt] ")"
# | typename-specifier braced-init-list
self.skip_ws()
if self.current_char != '(' and self.current_char != '{':
self.fail("Expecting '(' or '{' after type in cast expression.")
except DefinitionError as eInner:
typ = self._parse_type(False)
prefix = ASTTypeId(typ, isType=True)
if not self.skip_string(')'):
self.fail("Expected ')' to end 'typeid' of type.")
except DefinitionError as eType:
self.pos = pos
header = "Error in postfix expression, expected primary expression or type."
errors = []
errors.append((eOuter, "If primary expression"))
errors.append((eInner, "If type"))
raise self._make_multi_error(errors, header)
try:
def parser():
return self._parse_expression(inTemplate=False)
expr = self._parse_expression_fallback([')'], parser)
prefix = ASTTypeId(expr, isType=False)
if not self.skip_string(')'):
self.fail("Expected ')' to end 'typeid' of expression.")
except DefinitionError as eExpr:
self.pos = pos
header = "Error in 'typeid(...)'."
header += " Expected type or expression."
errors = []
errors.append((eType, "If type"))
errors.append((eExpr, "If expression"))
raise self._make_multi_error(errors, header)
else: # a primary expression or a type
pos = self.pos
try:
prefix = self._parse_primary_expression()
prefixType = 'expr'
except DefinitionError as eOuter:
self.pos = pos
try:
# we are potentially casting, so save parens for us
# TODO: hmm, would we need to try both with operatorCast and with None?
prefix = self._parse_type(False, 'operatorCast')
prefixType = 'typeOperatorCast'
# | simple-type-specifier "(" expression-list [opt] ")"
# | simple-type-specifier braced-init-list
# | typename-specifier "(" expression-list [opt] ")"
# | typename-specifier braced-init-list
self.skip_ws()
if self.current_char != '(' and self.current_char != '{':
self.fail("Expecting '(' or '{' after type in cast expression.")
except DefinitionError as eInner:
self.pos = pos
header = "Error in postfix expression,"
header += " expected primary expression or type."
errors = []
errors.append((eOuter, "If primary expression"))
errors.append((eInner, "If type"))
raise self._make_multi_error(errors, header)
# and now parse postfixes
postFixes = []
while True:
self.skip_ws()
if prefixType == 'expr':
if prefixType in ['expr', 'cast', 'typeid']:
if self.skip_string_and_ws('['):
expr = self._parse_expression(inTemplate=False)
self.skip_ws()

View File

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives
@ -21,8 +23,7 @@ from sphinx.roles import XRefRole
from sphinx.util.docfields import Field, GroupedField, TypedField
from sphinx.util.nodes import make_refnode
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Iterator, List, Tuple # NOQA
from docutils import nodes # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -10,6 +10,7 @@
"""
import re
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives
@ -24,8 +25,7 @@ from sphinx.util import logging
from sphinx.util.docfields import Field, GroupedField, TypedField
from sphinx.util.nodes import make_refnode
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Iterable, Iterator, List, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA

View File

@ -10,6 +10,7 @@
"""
import re
from typing import TYPE_CHECKING
from six import iteritems
@ -20,8 +21,7 @@ from sphinx.locale import l_, _
from sphinx.roles import XRefRole
from sphinx.util.nodes import make_refnode
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Iterator, List, Tuple # NOQA
from docutils import nodes # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -11,6 +11,8 @@
import re
import unicodedata
from copy import copy
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives
@ -25,8 +27,7 @@ from sphinx.roles import XRefRole
from sphinx.util import ws_re, logging, docname_join
from sphinx.util.nodes import clean_astext, make_refnode
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Iterator, List, Tuple, Type, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA
@ -522,6 +523,15 @@ class StandardDomain(Domain):
nodes.container: ('code-block', None),
} # type: Dict[nodes.Node, Tuple[unicode, Callable]]
def __init__(self, env):
# type: (BuildEnvironment) -> None
super(StandardDomain, self).__init__(env)
# set up enumerable nodes
self.enumerable_nodes = copy(self.enumerable_nodes) # create a copy for this instance
for node, settings in iteritems(env.app.registry.enumerable_nodes):
self.enumerable_nodes[node] = settings
def clear_doc(self, docname):
# type: (unicode) -> None
for key, (fn, _l) in list(self.data['progoptions'].items()):

View File

@ -18,6 +18,7 @@ import warnings
from collections import defaultdict
from copy import copy
from os import path
from typing import TYPE_CHECKING
from docutils.frontend import OptionParser
from docutils.utils import Reporter, get_source_line
@ -42,8 +43,7 @@ from sphinx.util.osutil import SEP, ensuredir
from sphinx.util.parallel import ParallelTasks, parallel_available, make_chunks
from sphinx.util.websupport import is_commentable
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, IO, Iterator, List, Optional, Pattern, Set, Tuple, Type, Union, Generator # NOQA
from docutils import nodes # NOQA
from sphinx.application import Sphinx # NOQA
@ -165,8 +165,8 @@ class BuildEnvironment(object):
# type: (Sphinx) -> None
self.app = app
self.doctreedir = app.doctreedir
self.srcdir = app.srcdir
self.config = app.config
self.srcdir = app.srcdir # type: unicode
self.config = app.config # type: Config
# the method of doctree versioning; see set_versioning_method
self.versioning_condition = None # type: Union[bool, Callable]
@ -183,7 +183,7 @@ class BuildEnvironment(object):
self._warnfunc = None # type: Callable
# this is to invalidate old pickles
self.version = app.registry.get_envversion(app)
self.version = app.registry.get_envversion(app) # type: Dict[unicode, unicode]
# All "docnames" here are /-separated and relative and exclude
# the source suffix.
@ -248,8 +248,8 @@ class BuildEnvironment(object):
# lineno, module, descname, content)
# these map absolute path -> (docnames, unique filename)
self.images = FilenameUniqDict()
self.dlfiles = FilenameUniqDict()
self.images = FilenameUniqDict() # type: FilenameUniqDict
self.dlfiles = FilenameUniqDict() # type: FilenameUniqDict
# the original URI for images
self.original_image_uri = {} # type: Dict[unicode, unicode]

View File

@ -9,8 +9,9 @@
:license: BSD, see LICENSE for details.
"""
if False:
# For type annotation
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from sphinx.environment import BuildEnvironment # NOQA

View File

@ -12,14 +12,14 @@ import bisect
import re
import unicodedata
from itertools import groupby
from typing import TYPE_CHECKING
from six import text_type, iteritems
from sphinx.locale import _
from sphinx.util import split_into, logging
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Pattern, List, Tuple # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from six import iteritems
@ -16,8 +18,7 @@ from sphinx import addnodes
from sphinx.util import url_re, logging
from sphinx.util.nodes import clean_astext, process_only_nodes
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@ -9,10 +9,11 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from six import itervalues
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Dict, List, Set # NOQA
from docutils import nodes # NOQA
from sphinx.sphinx import Sphinx # NOQA

View File

@ -12,6 +12,7 @@
import os
from glob import glob
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.utils import relative_path
@ -23,8 +24,7 @@ from sphinx.util import logging
from sphinx.util.i18n import get_image_filename_for_language, search_image_for_language
from sphinx.util.images import guess_mimetype
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Dict, List, Set, Tuple # NOQA
from docutils import nodes # NOQA
from sphinx.sphinx import Sphinx # NOQA

View File

@ -10,14 +10,14 @@
"""
from os import path
from typing import TYPE_CHECKING
from docutils.utils import relative_path
from sphinx.environment.collectors import EnvironmentCollector
from sphinx.util.osutil import getcwd, fs_encoding
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Dict, Set # NOQA
from docutils import nodes # NOQA
from sphinx.sphinx import Sphinx # NOQA

View File

@ -9,12 +9,13 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from sphinx import addnodes
from sphinx.environment.collectors import EnvironmentCollector
from sphinx.util import split_index_msg, logging
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Dict, Set # NOQA
from docutils import nodes # NOQA
from sphinx.applicatin import Sphinx # NOQA

View File

@ -9,12 +9,13 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from sphinx.environment.collectors import EnvironmentCollector
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Dict, Set # NOQA
from docutils import nodes # NOQA
from sphinx.sphinx import Sphinx # NOQA

View File

@ -9,13 +9,14 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from sphinx.environment.collectors import EnvironmentCollector
from sphinx.transforms import SphinxContentsFilter
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Dict, Set # NOQA
from docutils import nodes # NOQA
from sphinx.sphinx import Sphinx # NOQA

View File

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from six import iteritems
@ -18,8 +20,7 @@ from sphinx.environment.collectors import EnvironmentCollector
from sphinx.transforms import SphinxContentsFilter
from sphinx.util import url_re, logging
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Set, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA

View File

@ -10,8 +10,9 @@
:license: BSD, see LICENSE for details.
"""
if False:
# For type annotation
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Any # NOQA

View File

@ -13,14 +13,14 @@
from __future__ import print_function
from collections import OrderedDict, defaultdict
from typing import TYPE_CHECKING
from six import itervalues
from sphinx.errors import ExtensionError
from sphinx.locale import __
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, List # NOQA

View File

@ -23,6 +23,7 @@ import os
import sys
from fnmatch import fnmatch
from os import path
from typing import TYPE_CHECKING
from six import binary_type
@ -31,8 +32,7 @@ from sphinx.cmd.quickstart import EXTENSIONS
from sphinx.util import rst
from sphinx.util.osutil import FileAvoidWrite, ensuredir, walk
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, List, Tuple # NOQA
# automodule options

View File

@ -15,6 +15,7 @@ import inspect
import re
import sys
import warnings
from typing import TYPE_CHECKING
from docutils.statemachine import ViewList
from six import iteritems, itervalues, text_type, class_types, string_types
@ -34,13 +35,13 @@ from sphinx.util.inspect import Signature, isdescriptor, safe_getmembers, \
safe_getattr, object_description, is_builtin_class_method, \
isenumattribute, isclassmethod, isstaticmethod, getdoc
if False:
# For type annotation
if TYPE_CHECKING:
from types import ModuleType # NOQA
from typing import Any, Callable, Dict, Iterator, List, Sequence, Set, Tuple, Type, Union # NOQA
from docutils import nodes # NOQA
from docutils.utils import Reporter # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA
from sphinx.ext.autodoc.directive import DocumenterBridge # NOQA
logger = logging.getLogger(__name__)
@ -281,7 +282,7 @@ class Documenter(object):
def __init__(self, directive, name, indent=u''):
# type: (DocumenterBridge, unicode, unicode) -> None
self.directive = directive
self.env = directive.env
self.env = directive.env # type: BuildEnvironment
self.options = directive.genopt
self.name = name
self.indent = indent
@ -745,7 +746,7 @@ class Documenter(object):
# where the attribute documentation would actually be found in.
# This is used for situations where you have a module that collects the
# functions and classes of internal submodules.
self.real_modname = real_modname or self.get_real_modname()
self.real_modname = real_modname or self.get_real_modname() # type: str
# try to also get a source code analyzer for attribute docs
try:

View File

@ -7,6 +7,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.statemachine import ViewList
@ -17,8 +19,7 @@ from sphinx.util import logging
from sphinx.util.docutils import switch_source_input
from sphinx.util.nodes import nested_parse_with_titles
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Set, Type # NOQA
from docutils.statemachine import State, StateMachine, StringList # NOQA
from docutils.utils import Reporter # NOQA

View File

@ -15,14 +15,14 @@ import traceback
import warnings
from collections import namedtuple
from types import FunctionType, MethodType, ModuleType
from typing import TYPE_CHECKING
from six import PY2
from sphinx.util import logging
from sphinx.util.inspect import isenumclass, safe_getattr
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Generator, List, Optional # NOQA
logger = logging.getLogger(__name__)
@ -181,7 +181,7 @@ def import_object(modname, objpath, objtype='', attrgetter=safe_getattr, warning
if isinstance(real_exc, SystemExit):
errmsg += ('; the module executes module level statement '
'and it might call sys.exit().')
elif isinstance(real_exc, ImportError):
elif isinstance(real_exc, ImportError) and real_exc.args:
errmsg += '; the following exception was raised:\n%s' % real_exc.args[0]
else:
errmsg += '; the following exception was raised:\n%s' % traceback_msg

View File

@ -11,14 +11,14 @@
import typing
import warnings
from typing import TYPE_CHECKING
from six import StringIO, string_types
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.util.inspect import object_description
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Tuple # NOQA

View File

@ -9,20 +9,21 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from sphinx.util import logging
from sphinx.util.nodes import clean_astext
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA
logger = logging.getLogger(__name__)
if False:
if TYPE_CHECKING:
# For type annotation
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -58,25 +58,29 @@ import os
import posixpath
import re
import sys
import warnings
from types import ModuleType
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from docutils.parsers.rst.states import RSTStateMachine, state_classes
from docutils.statemachine import ViewList
from six import string_types
from six import text_type
import sphinx
from sphinx import addnodes
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.environment.adapters.toctree import TocTree
from sphinx.ext.autodoc import get_documenters
from sphinx.ext.autodoc.directive import DocumenterBridge, Options
from sphinx.ext.autodoc.importer import import_module
from sphinx.pycode import ModuleAnalyzer, PycodeError
from sphinx.util import import_object, rst, logging
from sphinx.util.docutils import new_document
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple, Type, Union # NOQA
from docutils.utils import Inliner # NOQA
from sphinx.application import Sphinx # NOQA
@ -154,14 +158,18 @@ def autosummary_table_visit_html(self, node):
# -- autodoc integration -------------------------------------------------------
# current application object (used in `get_documenter()`).
_app = None # type: Sphinx
class FakeDirective(DocumenterBridge):
def __init__(self):
# type: () -> None
super(FakeDirective, self).__init__({}, None, Options(), 0) # type: ignore
def get_documenter(app, obj, parent):
# type: (Sphinx, Any, Any) -> Type[Documenter]
def get_documenter(*args):
# type: (Any) -> Type[Documenter]
"""Get an autodoc.Documenter class suitable for documenting the given
object.
@ -170,6 +178,16 @@ def get_documenter(app, obj, parent):
belongs to.
"""
from sphinx.ext.autodoc import DataDocumenter, ModuleDocumenter
if len(args) == 3:
# new style arguments: (app, obj, parent)
app, obj, parent = args
else:
# old style arguments: (obj, parent)
app = _app
obj, parent = args
warnings.warn('the interface of get_documenter() has been changed. '
'Please give application object as first argument.',
RemovedInSphinx20Warning)
if inspect.ismodule(obj):
# ModuleDocumenter.can_document_member always returns False
@ -326,27 +344,7 @@ class Autosummary(Directive):
# -- Grab the summary
documenter.add_content(None)
doc = self.result.data
while doc and not doc[0].strip():
doc.pop(0)
# If there's a blank line, then we can assume the first sentence /
# paragraph has ended, so anything after shouldn't be part of the
# summary
for i, piece in enumerate(doc):
if not piece.strip():
doc = doc[:i]
break
# Try to find the "first sentence", which may span multiple lines
m = re.search(r"^([A-Z].*?\.)(?:\s|$)", " ".join(doc).strip())
if m:
summary = m.group(1).strip()
elif doc:
summary = doc[0].strip()
else:
summary = ''
summary = extract_summary(self.result.data[:], self.state.document)
items.append((display_name, sig, summary, real_name))
@ -453,6 +451,40 @@ def mangle_signature(sig, max_chars=30):
return u"(%s)" % sig
def extract_summary(doc, document):
# type: (List[unicode], Any) -> unicode
"""Extract summary from docstring."""
# Skip a blank lines at the top
while doc and not doc[0].strip():
doc.pop(0)
# If there's a blank line, then we can assume the first sentence /
# paragraph has ended, so anything after shouldn't be part of the
# summary
for i, piece in enumerate(doc):
if not piece.strip():
doc = doc[:i]
break
# Try to find the "first sentence", which may span multiple lines
sentences = " ".join(doc).split('.')
if len(sentences) == 1:
summary = sentences[0].strip()
else:
summary = ''
state_machine = RSTStateMachine(state_classes, 'Body')
while sentences:
summary += sentences.pop(0) + '.'
node = new_document('', document.settings)
state_machine.run([summary], node)
if not node.traverse(nodes.system_message):
# considered as that splitting by period does not break inline markups
break
return summary
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
# type: (unicode, List[unicode], int, unicode) -> unicode
"""Join a number of strings to one, limiting the length to *max_chars*.

View File

@ -25,6 +25,7 @@ import os
import pydoc
import re
import sys
from typing import TYPE_CHECKING
from jinja2 import FileSystemLoader, TemplateNotFound
from jinja2.sandbox import SandboxedEnvironment
@ -38,8 +39,7 @@ from sphinx.util.inspect import safe_getattr
from sphinx.util.osutil import ensuredir
from sphinx.util.rst import escape as rst_escape
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Tuple, List # NOQA
from jinja2 import BaseLoader # NOQA
from sphinx import addnodes # NOQA

View File

@ -14,6 +14,7 @@ import glob
import inspect
import re
from os import path
from typing import TYPE_CHECKING
from six import iteritems
from six.moves import cPickle as pickle
@ -23,8 +24,7 @@ from sphinx.builders import Builder
from sphinx.util import logging
from sphinx.util.inspect import safe_getattr
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, IO, List, Pattern, Set, Tuple # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -17,6 +17,7 @@ import re
import sys
import time
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives
@ -32,8 +33,7 @@ from sphinx.util.console import bold # type: ignore
from sphinx.util.nodes import set_source_info
from sphinx.util.osutil import fs_encoding
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, IO, Iterable, List, Optional, Sequence, Set, Tuple # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -24,14 +24,15 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes, utils
from six import iteritems
import sphinx
from sphinx.util.nodes import split_explicit_title
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple # NOQA
from docutils.parsers.rst.states import Inliner # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -10,11 +10,11 @@
"""
import os
from typing import TYPE_CHECKING
import sphinx
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@ -16,6 +16,7 @@ import re
from hashlib import sha1
from os import path
from subprocess import Popen, PIPE
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives
@ -29,8 +30,7 @@ from sphinx.util import logging
from sphinx.util.i18n import search_image_for_language
from sphinx.util.osutil import ensuredir, ENOENT, EPIPE, EINVAL
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
@ -341,7 +341,7 @@ def render_dot_latex(self, node, code, options, prefix='graphviz'):
post = r'\hspace*{\fill}}'
self.body.append('\n%s' % pre)
self.body.append(r'\includegraphics{%s}' % fname)
self.body.append(r'\sphinxincludegraphics[]{%s}' % fname)
if not is_inline:
self.body.append('%s\n' % post)

View File

@ -20,14 +20,15 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive
import sphinx
from sphinx.util.nodes import set_source_info
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -9,6 +9,7 @@
:license: BSD, see LICENSE for details.
"""
import subprocess
from typing import TYPE_CHECKING
from sphinx.errors import ExtensionError
from sphinx.locale import __
@ -16,8 +17,7 @@ from sphinx.transforms.post_transforms.images import ImageConverter
from sphinx.util import logging
from sphinx.util.osutil import ENOENT, EPIPE, EINVAL
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -17,6 +17,7 @@ import tempfile
from hashlib import sha1
from os import path
from subprocess import Popen, PIPE
from typing import TYPE_CHECKING
from docutils import nodes
from six import text_type
@ -31,8 +32,7 @@ from sphinx.util.osutil import ensuredir, ENOENT, cd
from sphinx.util.png import read_png_depth, write_png_depth
from sphinx.util.pycompat import sys_encoding
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA

View File

@ -40,6 +40,7 @@ import inspect
import re
import sys
from hashlib import md5
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive, directives
@ -52,8 +53,7 @@ from sphinx.ext.graphviz import render_dot_html, render_dot_latex, \
from sphinx.pycode import ModuleAnalyzer
from sphinx.util import force_decode
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple, Dict, Optional # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@ -30,7 +30,9 @@ import functools
import posixpath
import sys
import time
import warnings
from os import path
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.utils import relative_path
@ -39,12 +41,12 @@ from six.moves.urllib.parse import urlsplit, urlunsplit
import sphinx
from sphinx.builders.html import INVENTORY_FILENAME
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.locale import _
from sphinx.util import requests, logging
from sphinx.util.inventory import InventoryFile
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, IO, List, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA
@ -381,7 +383,16 @@ def setup(app):
def debug(argv):
# type: (List[unicode]) -> None
"""Debug functionality to print out an inventory"""
if len(argv) < 2:
warnings.warn('sphinx.ext.intersphinx.debug() is deprecated. '
'Please use inspect_main() instead',
RemovedInSphinx20Warning)
inspect_main(argv[1:])
def inspect_main(argv):
# type: (List[unicode]) -> None
"""Debug functionality to print out an inventory"""
if len(argv) < 1:
print("Print out an inventory file.\n"
"Error: must specify local path or URL to an inventory file.",
file=sys.stderr)
@ -399,7 +410,7 @@ def debug(argv):
# type: (unicode) -> None
print(msg, file=sys.stderr)
filename = argv[1]
filename = argv[0]
invdata = fetch_inventory(MockApp(), '', filename) # type: ignore
for key in sorted(invdata or {}):
print(key)
@ -413,4 +424,4 @@ if __name__ == '__main__':
import logging # type: ignore
logging.basicConfig()
debug(argv=sys.argv[1:]) # type: ignore
inspect_main(argv=sys.argv[1:]) # type: ignore

View File

@ -10,6 +10,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
import sphinx
@ -19,8 +21,7 @@ from sphinx.ext.mathbase import setup_math as mathbase_setup
from sphinx.locale import _
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
import sphinx
@ -16,8 +18,7 @@ from sphinx import addnodes
from sphinx.errors import SphinxError
from sphinx.locale import _
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Set # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes, utils
from docutils.nodes import make_id
from docutils.parsers.rst import Directive, directives
@ -20,8 +22,7 @@ from sphinx.roles import XRefRole
from sphinx.util import logging
from sphinx.util.nodes import make_refnode, set_source_info
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Iterable, List, Tuple # NOQA
from docutils.parsers.rst.states import Inliner # NOQA
from docutils.writers.html4css1 import Writer # NOQA

View File

@ -11,6 +11,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
import sphinx
@ -19,9 +21,7 @@ from sphinx.ext.mathbase import get_node_equation_number
from sphinx.ext.mathbase import setup_math as mathbase_setup
from sphinx.locale import _
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -10,6 +10,7 @@
"""
import sys
from typing import TYPE_CHECKING
from six import PY2, iteritems
@ -17,8 +18,7 @@ import sphinx
from sphinx.application import Sphinx
from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List # NOQA
@ -47,6 +47,7 @@ class Config(object):
napoleon_use_param = True
napoleon_use_rtype = True
napoleon_use_keyword = True
napoleon_custom_sections = None
.. _Google style:
https://google.github.io/styleguide/pyguide.html
@ -241,6 +242,19 @@ class Config(object):
:returns: *bool* -- True if successful, False otherwise
napoleon_custom_sections : :obj:`list` (Defaults to None)
Add a list of custom sections to include, expanding the list of parsed sections.
The entries can either be strings or tuples, depending on the intention:
* To create a custom "generic" section, just pass a string.
* To create an alias for an existing section, pass a tuple containing the
alias name and the original, in that order.
If an entry is just a string, it is interpreted as a header for a generic
section. If the entry is a tuple/list/indexed container, the first entry
is the name of the section, the second is the section key to emulate.
"""
_config_values = {
'napoleon_google_docstring': (True, 'env'),
@ -254,7 +268,8 @@ class Config(object):
'napoleon_use_ivar': (False, 'env'),
'napoleon_use_param': (True, 'env'),
'napoleon_use_rtype': (True, 'env'),
'napoleon_use_keyword': (True, 'env')
'napoleon_use_keyword': (True, 'env'),
'napoleon_custom_sections': (None, 'env')
}
def __init__(self, **settings):

View File

@ -15,6 +15,7 @@ import collections
import inspect
import re
from functools import partial
from typing import TYPE_CHECKING
from six import string_types, u
from six.moves import range
@ -22,8 +23,7 @@ from six.moves import range
from sphinx.ext.napoleon.iterators import modify_iter
from sphinx.util.pycompat import UnicodeMixin
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, List, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config as SphinxConfig # NOQA
@ -170,6 +170,9 @@ class GoogleDocstring(UnicodeMixin):
'yield': self._parse_yields_section,
'yields': self._parse_yields_section,
} # type: Dict[unicode, Callable]
self._load_custom_sections()
self._parse()
def __unicode__(self):
@ -530,6 +533,23 @@ class GoogleDocstring(UnicodeMixin):
line and
not self._is_indented(line, self._section_indent)))
def _load_custom_sections(self):
# type: () -> None
if self._config.napoleon_custom_sections is not None:
for entry in self._config.napoleon_custom_sections:
if isinstance(entry, string_types):
# if entry is just a label, add to sections list,
# using generic section logic.
self._sections[entry.lower()] = self._parse_custom_generic_section
else:
# otherwise, assume entry is container;
# [0] is new section, [1] is the section to alias.
# in the case of key mismatch, just handle as generic section.
self._sections[entry[0].lower()] = \
self._sections.get(entry[1].lower(),
self._parse_custom_generic_section)
def _parse(self):
# type: () -> None
self._parsed_lines = self._consume_empty()
@ -597,6 +617,10 @@ class GoogleDocstring(UnicodeMixin):
use_admonition = self._config.napoleon_use_admonition_for_examples
return self._parse_generic_section(section, use_admonition)
def _parse_custom_generic_section(self, section):
# for now, no admonition for simple custom sections
return self._parse_generic_section(section, False)
def _parse_usage_section(self, section):
# type: (unicode) -> List[unicode]
header = ['.. rubric:: Usage:', ''] # type: List[unicode]

View File

@ -12,9 +12,9 @@
"""
import collections
from typing import TYPE_CHECKING
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Iterable # NOQA

View File

@ -18,6 +18,7 @@ import tempfile
from hashlib import sha1
from os import path
from subprocess import Popen, PIPE
from typing import TYPE_CHECKING
from docutils import nodes
from six import text_type
@ -31,8 +32,7 @@ from sphinx.util.osutil import ensuredir, ENOENT, cd
from sphinx.util.png import read_png_depth, write_png_depth
from sphinx.util.pycompat import sys_encoding
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.ext.mathbase import math as math_node, displaymath # NOQA

View File

@ -12,6 +12,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives
@ -24,8 +26,7 @@ from sphinx.util import logging
from sphinx.util.nodes import set_source_info
from sphinx.util.texescape import tex_escape_map
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Iterable, List # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@ -10,6 +10,7 @@
"""
import traceback
from typing import TYPE_CHECKING
from docutils import nodes
from six import iteritems, text_type
@ -21,8 +22,7 @@ from sphinx.pycode import ModuleAnalyzer
from sphinx.util import get_full_modname, logging, status_iterator
from sphinx.util.nodes import make_refnode
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, Iterable, Iterator, Set, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@ -9,14 +9,15 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from six import iteritems
from sphinx.errors import VersionRequirementError
from sphinx.locale import __
from sphinx.util import logging
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA

View File

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
from pygments import highlight
from pygments.filters import ErrorToken
from pygments.formatters import HtmlFormatter, LatexFormatter
@ -26,8 +28,7 @@ from sphinx.util import logging
from sphinx.util.pycompat import htmlescape
from sphinx.util.texescape import tex_hl_escape_map_new
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict # NOQA
from pygments.formatter import Formatter # NOQA

View File

@ -10,6 +10,7 @@
"""
import codecs
import re
from typing import TYPE_CHECKING
from docutils.core import Publisher
from docutils.io import FileInput, NullOutput
@ -33,8 +34,7 @@ from sphinx.transforms.i18n import (
from sphinx.util import logging
from sphinx.util.docutils import LoggingReporter
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple, Union # NOQA
from docutils import nodes # NOQA
from docutils.io import Input # NOQA
@ -305,7 +305,7 @@ def read_doc(app, env, filename):
source_class=SphinxDummySourceClass,
destination=NullOutput())
pub.set_components(None, 'restructuredtext', None)
pub.process_programmatic_settings(None, env.settings, None)
pub.process_programmatic_settings(None, env.settings, None) # type: ignore
pub.set_source(source, filename)
pub.publish()
return pub.document

View File

@ -11,7 +11,7 @@
from os import path
from pprint import pformat
from typing import Any, Callable, Iterator, Tuple # NOQA
from typing import TYPE_CHECKING, Any, Callable, Iterator, Tuple # NOQA
from jinja2 import FileSystemLoader, BaseLoader, TemplateNotFound, \
contextfunction
@ -22,8 +22,7 @@ from six import string_types
from sphinx.application import TemplateBridge
from sphinx.util.osutil import mtimes_of_files
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, List, Iterator, Tuple, Union # NOQA
from jinja2.environment import Environment # NOQA
from sphinx.builders import Builder # NOQA

View File

@ -10,12 +10,12 @@
"""
import gettext
from typing import TYPE_CHECKING
from six import PY3, text_type
from six.moves import UserString
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Iterator, List, Tuple # NOQA

View File

@ -1293,17 +1293,17 @@ msgstr "Treść"
#: sphinx/transforms/post_transforms/__init__.py:139
#, python-format
msgid "more than one target found for 'any' cross-reference %r: could be %s"
msgstr "znaleziono więcej niż jeden cel dla cross-referencji „any”: może być %s"
msgstr "znaleziono więcej niż jeden cel dla cross-referencji „any” %r: może być %s"
#: sphinx/transforms/post_transforms/__init__.py:169
#, python-format
msgid "%s:%s reference target not found: %%(target)s"
msgstr "nie znaleziono celu referencji %s:%s: %%(cel)e"
msgstr "nie znaleziono celu referencji %s:%s: %%(target)s"
#: sphinx/transforms/post_transforms/__init__.py:172
#, python-format
msgid "%r reference target not found: %%(target)s"
msgstr "nie znaleziono celu referencji %r: %%(cel)e"
msgstr "nie znaleziono celu referencji %r: %%(target)s"
#: sphinx/util/docutils.py:202
msgid "when adding directive classes, no additional arguments may be given"

View File

@ -20,14 +20,14 @@ import os
import subprocess
import sys
from os import path
from typing import TYPE_CHECKING
import sphinx
from sphinx import cmdline
from sphinx.util.console import color_terminal, nocolor, bold, blue # type: ignore
from sphinx.util.osutil import cd, rmtree
if False:
# For type annotation
if TYPE_CHECKING:
from typing import List # NOQA
proj_name = os.getenv('SPHINXPROJ', '<project>')

View File

@ -9,14 +9,15 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING
import docutils.parsers
import docutils.parsers.rst
from docutils.parsers.rst import states
from docutils.statemachine import StringList
from docutils.transforms.universal import SmartQuotes
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Type # NOQA
from docutils import nodes # NOQA
from docutils.transforms import Transform # NOQA
@ -91,7 +92,7 @@ class RSTParser(docutils.parsers.rst.Parser):
def setup(app):
# type: (Sphinx) -> Dict[unicode, Any]
app.add_source_parser('.rst', RSTParser)
app.add_source_parser(RSTParser)
return {
'version': 'builtin',

View File

@ -10,14 +10,15 @@
"""
from __future__ import print_function
from typing import TYPE_CHECKING
from six import iteritems, BytesIO, StringIO
from sphinx.errors import PycodeError
from sphinx.pycode.parser import Parser
from sphinx.util import get_module_source, detect_encoding
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, IO, List, Tuple # NOQA

View File

@ -15,11 +15,11 @@ import re
import tokenize
from token import NAME, NEWLINE, INDENT, DEDENT, NUMBER, OP, STRING
from tokenize import COMMENT, NL
from typing import TYPE_CHECKING
from six import PY2, text_type
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, IO, List, Tuple # NOQA
comment_re = re.compile(u'^\\s*#: ?(.*)\r?\n?$')

View File

@ -10,12 +10,12 @@
"""
import warnings
from typing import TYPE_CHECKING
from sphinx.cmd.quickstart import main as _main
from sphinx.deprecation import RemovedInSphinx20Warning
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any # NOQA
@ -27,6 +27,7 @@ def main(*args, **kwargs):
RemovedInSphinx20Warning,
stacklevel=2,
)
args = args[1:] # skip first argument to adjust arguments (refs: #4615)
_main(*args, **kwargs)

View File

@ -12,7 +12,11 @@ from __future__ import print_function
import traceback
import warnings
from inspect import isclass
from types import MethodType
from typing import TYPE_CHECKING
from docutils.parsers.rst import Directive
from pkg_resources import iter_entry_points
from six import iteritems, itervalues
@ -28,9 +32,8 @@ from sphinx.util import logging
from sphinx.util.console import bold # type: ignore
from sphinx.util.docutils import directive_helper
if False:
# For type annotation
from typing import Any, Callable, Dict, Iterator, List, Type, Union # NOQA
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Iterator, List, Tuple, Type, Union # NOQA
from docutils import nodes # NOQA
from docutils.io import Input # NOQA
from docutils.parsers import Parser # NOQA
@ -40,7 +43,7 @@ if False:
from sphinx.domains import Domain, Index # NOQA
from sphinx.environment import BuildEnvironment # NOQA
from sphinx.ext.autodoc import Documenter # NOQA
from sphinx.util.typing import RoleFunction # NOQA
from sphinx.util.typing import RoleFunction, TitleGetter # NOQA
logger = logging.getLogger(__name__)
@ -82,6 +85,13 @@ class SphinxComponentRegistry(object):
#: a dict of domain name -> dict of role name -> role impl.
self.domain_roles = {} # type: Dict[unicode, Dict[unicode, Union[RoleFunction, XRefRole]]] # NOQA
#: additional enumerable nodes
#: a dict of node class -> tuple of figtype and title_getter function
self.enumerable_nodes = {} # type: Dict[nodes.Node, Tuple[unicode, TitleGetter]]
#: LaTeX packages; list of package names and its options
self.latex_packages = [] # type: List[Tuple[unicode, unicode]]
#: post transforms; list of transforms
self.post_transforms = [] # type: List[Type[Transform]]
@ -97,6 +107,10 @@ class SphinxComponentRegistry(object):
#: custom translators; builder name -> translator class
self.translators = {} # type: Dict[unicode, nodes.NodeVisitor]
#: custom handlers for translators
#: a dict of builder name -> dict of node name -> visitor and departure functions
self.translation_handlers = {} # type: Dict[unicode, Dict[unicode, Tuple[Callable, Callable]]] # NOQA
#: additional transforms; list of transforms
self.transforms = [] # type: List[Type[Transform]]
@ -174,8 +188,12 @@ class SphinxComponentRegistry(object):
(domain, name, obj, has_content, argument_spec, option_spec))
if domain not in self.domains:
raise ExtensionError(__('domain %s not yet registered') % domain)
directives = self.domain_directives.setdefault(domain, {})
directives[name] = directive_helper(obj, has_content, argument_spec, **option_spec)
if not isclass(obj) or not issubclass(obj, Directive):
directives[name] = directive_helper(obj, has_content, argument_spec, **option_spec)
else:
directives[name] = obj
def add_role_to_domain(self, domain, name, role):
# type: (unicode, unicode, Union[RoleFunction, XRefRole]) -> None
@ -239,10 +257,23 @@ class SphinxComponentRegistry(object):
else:
self.source_suffix[suffix] = filetype
def add_source_parser(self, suffix, parser):
# type: (unicode, Type[Parser]) -> None
logger.debug('[app] adding search source_parser: %r, %r', suffix, parser)
self.add_source_suffix(suffix, suffix)
def add_source_parser(self, *args):
# type: (Any) -> None
logger.debug('[app] adding search source_parser: %r', args)
if len(args) == 1:
# new sytle arguments: (source_parser)
suffix = None # type: unicode
parser = args[0] # type: Type[Parser]
else:
# old style arguments: (suffix, source_parser)
warnings.warn('app.add_source_parser() does not support suffix argument. '
'Use app.add_source_suffix() instead.',
RemovedInSphinx30Warning)
suffix = args[0]
parser = args[1]
if suffix:
self.add_source_suffix(suffix, suffix)
if len(parser.supported) == 0:
warnings.warn('Old source_parser has been detected. Please fill Parser.supported '
@ -259,8 +290,9 @@ class SphinxComponentRegistry(object):
# also maps suffix to parser
#
# This allows parsers not having ``supported`` filetypes.
self.source_parsers[suffix] = parser
# This rescues old styled parsers which does not have ``supported`` filetypes.
if suffix:
self.source_parsers[suffix] = parser
def get_source_parser(self, filetype):
# type: (unicode) -> Type[Parser]
@ -305,15 +337,41 @@ class SphinxComponentRegistry(object):
logger.info(bold(__('Change of translator for the %s builder.') % name))
self.translators[name] = translator
def add_translation_handlers(self, node, **kwargs):
# type: (nodes.Node, Any) -> None
logger.debug('[app] adding translation_handlers: %r, %r', node, kwargs)
for builder_name, handlers in iteritems(kwargs):
translation_handlers = self.translation_handlers.setdefault(builder_name, {})
try:
visit, depart = handlers # unpack once for assertion
translation_handlers[node.__name__] = (visit, depart)
except ValueError:
raise ExtensionError(__('kwargs for add_node() must be a (visit, depart) '
'function tuple: %r=%r') % builder_name, handlers)
def get_translator_class(self, builder):
# type: (Builder) -> Type[nodes.NodeVisitor]
return self.translators.get(builder.name,
builder.default_translator_class)
def create_translator(self, builder, document):
# type: (Builder, nodes.Node) -> nodes.NodeVisitor
def create_translator(self, builder, *args):
# type: (Builder, Any) -> nodes.NodeVisitor
translator_class = self.get_translator_class(builder)
return translator_class(builder, document)
assert translator_class, "translator not found for %s" % builder.name
translator = translator_class(*args)
# transplant handlers for custom nodes to translator instance
handlers = self.translation_handlers.get(builder.name, None)
if handlers is None:
# retry with builder.format
handlers = self.translation_handlers.get(builder.format, {})
for name, (visit, depart) in iteritems(handlers):
setattr(translator, 'visit_' + name, MethodType(visit, translator))
if depart:
setattr(translator, 'depart_' + name, MethodType(depart, translator))
return translator
def add_transform(self, transform):
# type: (Type[Transform]) -> None
@ -341,6 +399,16 @@ class SphinxComponentRegistry(object):
# type: (Type, Callable[[Any, unicode, Any], Any]) -> None
self.autodoc_attrgettrs[typ] = attrgetter
def add_latex_package(self, name, options):
# type: (unicode, unicode) -> None
logger.debug('[app] adding latex package: %r', name)
self.latex_packages.append((name, options))
def add_enumerable_node(self, node, figtype, title_getter=None):
# type: (nodes.Node, unicode, TitleGetter) -> None
logger.debug('[app] adding enumerable node: (%r, %r, %r)', node, figtype, title_getter)
self.enumerable_nodes[node] = (figtype, title_getter)
def load_extension(self, app, extname):
# type: (Sphinx, unicode) -> None
"""Load a Sphinx extension."""
@ -398,13 +466,13 @@ class SphinxComponentRegistry(object):
def merge_source_suffix(app):
# type: (Sphinx) -> None
"""Merge source_suffix which specified by user and added by extensions."""
for suffix in app.registry.source_suffix:
for suffix, filetype in iteritems(app.registry.source_suffix):
if suffix not in app.config.source_suffix:
app.config.source_suffix[suffix] = suffix
app.config.source_suffix[suffix] = filetype
elif app.config.source_suffix[suffix] is None:
# filetype is not specified (default filetype).
# So it overrides default filetype by extensions setting.
app.config.source_suffix[suffix] = suffix
app.config.source_suffix[suffix] = filetype
# copy config.source_suffix to registry
app.registry.source_suffix = app.config.source_suffix

View File

@ -10,6 +10,7 @@
"""
import re
from typing import TYPE_CHECKING
from docutils import nodes, utils
from six import iteritems
@ -21,8 +22,7 @@ from sphinx.util import ws_re
from sphinx.util.nodes import split_explicit_title, process_index_entry, \
set_role_source_info
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, List, Tuple, Type # NOQA
from docutils.parsers.rst.states import Inliner # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -10,6 +10,7 @@
"""
import re
from os import path
from typing import TYPE_CHECKING
from six import iteritems, itervalues, text_type, string_types
from six.moves import cPickle as pickle
@ -21,8 +22,7 @@ from sphinx.util import jsdump, rpartition
from sphinx.util.pycompat import htmlescape
from sphinx.search.jssplitter import splitter_code
if False:
# For type annotation
if TYPE_CHECKING:
from typing import Any, Dict, IO, Iterable, List, Tuple, Type, Set # NOQA
from docutils import nodes # NOQA
from sphinx.environment import BuildEnvironment # NOQA

Some files were not shown because too many files have changed in this diff Show More