Merge pull request #5370 from tk0miya/drop_deprecated_methods

Drop APIs deprecated in 2.0
This commit is contained in:
Takeshi KOMIYA 2018-09-05 22:56:02 +09:00 committed by GitHub
commit aa3e590d5e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 25 additions and 980 deletions

View File

@ -115,32 +115,6 @@ Emitting events
.. automethod:: emit_firstresult(event, \*arguments)
Producing messages / logging
----------------------------
The application object also provides support for emitting leveled messages.
.. note::
There is no "error" call: in Sphinx, errors are defined as things that stop
the build; just raise an exception (:exc:`sphinx.errors.SphinxError` or a
custom subclass) to do that.
.. deprecated:: 1.6
Please use :ref:`logging-api` instead.
.. automethod:: Sphinx.warn
.. automethod:: Sphinx.info
.. automethod:: Sphinx.verbose
.. automethod:: Sphinx.debug
.. automethod:: Sphinx.debug2
Sphinx runtime information
--------------------------

View File

@ -39,10 +39,6 @@ Build environment API
**Utility methods**
.. automethod:: warn
.. automethod:: warn_node
.. automethod:: doc2path
.. automethod:: relfn2path

View File

@ -27,7 +27,6 @@ install_requires = [
'requests>=2.0.0',
'setuptools',
'packaging',
'sphinxcontrib-websupport',
]
extras_require = {

View File

@ -15,12 +15,10 @@
from __future__ import absolute_import
import os
import sys
import warnings
from os import path
from .deprecation import RemovedInNextVersionWarning
from .deprecation import RemovedInSphinx20Warning
if False:
# For type annotation
@ -68,47 +66,3 @@ if __version__.endswith('+'):
__display_version__ += '/' + out.decode().strip()
except Exception:
pass
def main(argv=sys.argv): # type: ignore
# type: (List[unicode]) -> int
from .cmd import build
warnings.warn(
'`sphinx.main()` has moved to `sphinx.cmd.build.main()`.',
RemovedInSphinx20Warning,
stacklevel=2,
)
argv = argv[1:] # skip first argument to adjust arguments (refs: #4615)
return build.main(argv)
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,
)
build.main()

View File

@ -1,41 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.apidoc
~~~~~~~~~~~~~
This file has moved to :py:mod:`sphinx.ext.apidoc`.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
import warnings
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.ext.apidoc import main as _main
if False:
# For type annotation
from typing import List # NOQA
from sphinx.application import Sphinx # NOQA
def main(argv=sys.argv):
# type: (List[str]) -> None
warnings.warn(
'`sphinx.apidoc.main()` has moved to `sphinx.ext.apidoc.main()`.',
RemovedInSphinx20Warning,
stacklevel=2,
)
_main(argv[1:]) # skip first argument to adjust arguments (refs: #4615)
# So program can be started with "python -m sphinx.apidoc ..."
if __name__ == "__main__":
warnings.warn(
'`sphinx.apidoc` has moved to `sphinx.ext.apidoc`.',
RemovedInSphinx20Warning,
stacklevel=2,
)
main()

View File

@ -29,7 +29,7 @@ from sphinx import package_dir, locale
from sphinx.config import Config, check_unicode
from sphinx.config import CONFIG_FILENAME # NOQA # for compatibility (RemovedInSphinx30)
from sphinx.deprecation import (
RemovedInSphinx20Warning, RemovedInSphinx30Warning, RemovedInSphinx40Warning
RemovedInSphinx30Warning, RemovedInSphinx40Warning
)
from sphinx.environment import BuildEnvironment
from sphinx.errors import ApplicationError, ConfigError, VersionRequirementError
@ -369,72 +369,6 @@ class Sphinx(object):
self.emit('build-finished', None)
self.builder.cleanup()
# ---- logging handling ----------------------------------------------------
def warn(self, message, location=None, type=None, subtype=None):
# type: (unicode, unicode, unicode, unicode) -> None
"""Emit a warning.
If *location* is given, it should either be a tuple of (*docname*,
*lineno*) or a string describing the location of the warning as well as
possible.
*type* and *subtype* are used to suppress warnings with
:confval:`suppress_warnings`.
.. deprecated:: 1.6
Use :mod:`sphinx.util.logging` instead.
"""
warnings.warn('app.warning() is now deprecated. Use sphinx.util.logging instead.',
RemovedInSphinx20Warning)
logger.warning(message, type=type, subtype=subtype, location=location)
def info(self, message='', nonl=False):
# type: (unicode, bool) -> None
"""Emit an informational message.
If *nonl* is true, don't emit a newline at the end (which implies that
more info output will follow soon.)
.. deprecated:: 1.6
Use :mod:`sphinx.util.logging` instead.
"""
warnings.warn('app.info() is now deprecated. Use sphinx.util.logging instead.',
RemovedInSphinx20Warning)
logger.info(message, nonl=nonl)
def verbose(self, message, *args, **kwargs):
# type: (unicode, Any, Any) -> None
"""Emit a verbose informational message.
.. deprecated:: 1.6
Use :mod:`sphinx.util.logging` instead.
"""
warnings.warn('app.verbose() is now deprecated. Use sphinx.util.logging instead.',
RemovedInSphinx20Warning)
logger.verbose(message, *args, **kwargs)
def debug(self, message, *args, **kwargs):
# type: (unicode, Any, Any) -> None
"""Emit a debug-level informational message.
.. deprecated:: 1.6
Use :mod:`sphinx.util.logging` instead.
"""
warnings.warn('app.debug() is now deprecated. Use sphinx.util.logging instead.',
RemovedInSphinx20Warning)
logger.debug(message, *args, **kwargs)
def debug2(self, message, *args, **kwargs):
# type: (unicode, Any, Any) -> None
"""Emit a lowlevel debug-level informational message.
.. deprecated:: 1.6
Use :mod:`sphinx.util.logging` instead.
"""
warnings.warn('app.debug2() is now deprecated. Use debug() instead.',
RemovedInSphinx20Warning)
logger.debug(message, *args, **kwargs)
# ---- general extensibility interface -------------------------------------
def setup_extension(self, extname):
@ -913,21 +847,6 @@ class Sphinx(object):
ref_nodeclass, objname, doc_field_types,
override=override)
def add_description_unit(self, directivename, rolename, indextemplate='',
parse_node=None, ref_nodeclass=None, objname='',
doc_field_types=[]):
# type: (unicode, unicode, unicode, Callable, nodes.Node, unicode, List) -> None
"""Deprecated alias for :meth:`add_object_type`.
.. deprecated:: 1.6
Use :meth:`add_object_type` instead.
"""
warnings.warn('app.add_description_unit() is now deprecated. '
'Use app.add_object_type() instead.',
RemovedInSphinx20Warning)
self.add_object_type(directivename, rolename, indextemplate, parse_node,
ref_nodeclass, objname, doc_field_types)
def add_crossref_type(self, directivename, rolename, indextemplate='',
ref_nodeclass=None, objname='', override=False):
# type: (unicode, unicode, unicode, nodes.Node, unicode, bool) -> None

View File

@ -10,13 +10,11 @@
"""
import time
import warnings
from os import path
from docutils import nodes
from six.moves import cPickle as pickle
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.environment import CONFIG_OK, CONFIG_CHANGED_REASON
from sphinx.environment.adapters.asset import ImageAdapter
from sphinx.errors import SphinxError
@ -97,8 +95,6 @@ class Builder(object):
self.app = app # type: Sphinx
self.env = None # type: BuildEnvironment
self.warn = app.warn # type: Callable
self.info = app.info # type: Callable
self.config = app.config # type: Config
self.tags = app.tags # type: Tags
self.tags.add(self.format)
@ -138,22 +134,6 @@ class Builder(object):
"""
return self.app.registry.create_translator(self, *args)
@property
def translator_class(self):
# type: () -> Callable[[Any], nodes.NodeVisitor]
"""Return a class of translator.
.. deprecated:: 1.6
"""
translator_class = self.app.registry.get_translator_class(self)
if translator_class is None and self.default_translator_class is None:
warnings.warn('builder.translator_class() is now deprecated. '
'Please use builder.create_translator() and '
'builder.default_translator_class instead.',
RemovedInSphinx20Warning)
return None
return self.create_translator
# helper methods
def init(self):
# type: () -> None

View File

@ -32,7 +32,7 @@ from sphinx import package_dir, __display_version__
from sphinx.application import ENV_PICKLE_FILENAME
from sphinx.builders import Builder
from sphinx.config import string_classes
from sphinx.deprecation import RemovedInSphinx20Warning, RemovedInSphinx30Warning
from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.environment.adapters.asset import ImageAdapter
from sphinx.environment.adapters.indexentries import IndexEntries
from sphinx.environment.adapters.toctree import TocTree
@ -92,53 +92,6 @@ def get_stable_hash(obj):
return md5(text_type(obj).encode('utf8')).hexdigest()
class CSSContainer(list):
"""The container for stylesheets.
To support the extensions which access the container directly, this wraps
the entry with Stylesheet class.
"""
def append(self, obj):
# type: (Union[unicode, Stylesheet]) -> None
if isinstance(obj, Stylesheet):
super(CSSContainer, self).append(obj)
else:
super(CSSContainer, self).append(Stylesheet(obj))
def insert(self, index, obj):
# type: (int, Union[unicode, Stylesheet]) -> None
warnings.warn('builder.css_files is deprecated. '
'Please use app.add_stylesheet() instead.',
RemovedInSphinx20Warning)
if isinstance(obj, Stylesheet):
super(CSSContainer, self).insert(index, obj)
else:
super(CSSContainer, self).insert(index, Stylesheet(obj))
def extend(self, other): # type: ignore
# type: (List[Union[unicode, Stylesheet]]) -> None
warnings.warn('builder.css_files is deprecated. '
'Please use app.add_stylesheet() instead.',
RemovedInSphinx20Warning)
for item in other:
self.append(item)
def __iadd__(self, other): # type: ignore
# type: (List[Union[unicode, Stylesheet]]) -> CSSContainer
warnings.warn('builder.css_files is deprecated. '
'Please use app.add_stylesheet() instead.',
RemovedInSphinx20Warning)
for item in other:
self.append(item)
return self
def __add__(self, other):
# type: (List[Union[unicode, Stylesheet]]) -> CSSContainer
ret = CSSContainer(self)
ret += other
return ret
class Stylesheet(text_type):
"""A metadata of stylesheet.
@ -311,7 +264,7 @@ class StandaloneHTMLBuilder(Builder):
super(StandaloneHTMLBuilder, self).__init__(app)
# CSS files
self.css_files = CSSContainer() # type: List[Dict[unicode, unicode]]
self.css_files = [] # type: List[Dict[unicode, unicode]]
# JS files
self.script_files = JSContainer() # type: List[JavaScript]
@ -341,9 +294,9 @@ class StandaloneHTMLBuilder(Builder):
self.use_index = self.get_builder_config('use_index', 'html')
if self.config.html_experimental_html5_writer and not html5_ready:
self.app.warn(('html_experimental_html5_writer is set, but current version '
'is old. Docutils\' version should be 0.13 or newer, but %s.') %
docutils.__version__)
logger.warning(__('html_experimental_html5_writer is set, but current version '
'is old. Docutils\' version should be 0.13 or newer, but %s.'),
docutils.__version__)
def create_build_info(self):
# type: () -> BuildInfo
@ -1085,14 +1038,6 @@ class StandaloneHTMLBuilder(Builder):
if sidebars is None:
# keep defaults
pass
elif isinstance(sidebars, string_types):
# 0.x compatible mode: insert custom sidebar before searchbox
customsidebar = sidebars
sidebars = None
warnings.warn('Now html_sidebars only allows list of sidebar '
'templates as a value. Support for a string value '
'will be removed at Sphinx-2.0.',
RemovedInSphinx20Warning)
ctx['sidebars'] = sidebars
ctx['customsidebar'] = customsidebar
@ -1162,7 +1107,7 @@ class StandaloneHTMLBuilder(Builder):
warnings.warn('The template function warn() was deprecated. '
'Use warning() instead.',
RemovedInSphinx30Warning)
self.warn(*args, **kwargs)
logger.warning(*args, **kwargs)
return '' # return empty string
ctx['warn'] = warn

View File

@ -17,10 +17,6 @@ if False:
from typing import Any, Dict, Type # NOQA
class RemovedInSphinx20Warning(DeprecationWarning):
pass
class RemovedInSphinx30Warning(PendingDeprecationWarning):
pass
@ -29,7 +25,7 @@ class RemovedInSphinx40Warning(PendingDeprecationWarning):
pass
RemovedInNextVersionWarning = RemovedInSphinx20Warning
RemovedInNextVersionWarning = RemovedInSphinx30Warning
class DeprecatedDict(dict):

View File

@ -4578,7 +4578,7 @@ class DefinitionParser(object):
return ASTCharLiteral(prefix, data)
except UnicodeDecodeError as e:
self.fail("Can not handle character literal. Internal error was: %s" % e)
except UnsupportedMultiCharacterCharLiteral as e:
except UnsupportedMultiCharacterCharLiteral:
self.fail("Can not handle character literal"
" resulting in multiple decoded characters.")

View File

@ -10,20 +10,17 @@
"""
import os
import re
import sys
import warnings
from collections import defaultdict
from copy import copy
from os import path
from docutils.utils import get_source_line
from six import BytesIO, next
from six.moves import cPickle as pickle, reduce
from sphinx import addnodes
from sphinx.deprecation import RemovedInSphinx20Warning, RemovedInSphinx30Warning
from sphinx.environment.adapters.indexentries import IndexEntries
from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.environment.adapters.toctree import TocTree
from sphinx.errors import SphinxError, BuildEnvironmentError, DocumentError, ExtensionError
from sphinx.locale import __
@ -125,9 +122,6 @@ class BuildEnvironment(object):
self.settings = default_settings.copy()
self.settings['env'] = self
# the function to write warning messages with
self._warnfunc = None # type: Callable
# All "docnames" here are /-separated and relative and exclude
# the source suffix.
@ -272,11 +266,6 @@ class BuildEnvironment(object):
# Allow to disable by 3rd party extension (workaround)
self.settings.setdefault('smart_quotes', True)
def set_warnfunc(self, func):
# type: (Callable) -> None
warnings.warn('env.set_warnfunc() is now deprecated. Use sphinx.util.logging instead.',
RemovedInSphinx20Warning)
def set_versioning_method(self, method, compare):
# type: (unicode, bool) -> None
"""This sets the doctree versioning method for this environment.
@ -296,21 +285,6 @@ class BuildEnvironment(object):
self.versioning_condition = condition
self.versioning_compare = compare
def warn(self, docname, msg, lineno=None, **kwargs):
# type: (unicode, unicode, int, Any) -> None
"""Emit a warning.
This differs from using ``app.warn()`` in that the warning may not
be emitted instantly, but collected for emitting all warnings after
the update of the environment.
"""
self.app.warn(msg, location=(docname, lineno), **kwargs) # type: ignore
def warn_node(self, msg, node, **kwargs):
# type: (unicode, nodes.Node, Any) -> None
"""Like :meth:`warn`, but with source information taken from *node*."""
self._warnfunc(msg, '%s:%s' % get_source_line(node), **kwargs)
def clear_doc(self, docname):
# type: (unicode) -> None
"""Remove all traces of a source file in the inventory."""
@ -564,32 +538,6 @@ class BuildEnvironment(object):
"""
self.reread_always.add(self.docname)
def note_toctree(self, docname, toctreenode):
# type: (unicode, addnodes.toctree) -> None
"""Note a TOC tree directive in a document and gather information about
file relations from it.
"""
warnings.warn('env.note_toctree() is deprecated. '
'Use sphinx.environment.adapters.toctree.TocTree instead.',
RemovedInSphinx20Warning)
TocTree(self).note(docname, toctreenode)
def get_toc_for(self, docname, builder):
# type: (unicode, Builder) -> Dict[unicode, nodes.Node]
"""Return a TOC nodetree -- for use on the same page only!"""
warnings.warn('env.get_toc_for() is deprecated. '
'Use sphinx.environment.adapters.toctre.TocTree instead.',
RemovedInSphinx20Warning)
return TocTree(self).get_toc_for(docname, builder)
def get_toctree_for(self, docname, builder, collapse, **kwds):
# type: (unicode, Builder, bool, Any) -> addnodes.toctree
"""Return the global TOC nodetree."""
warnings.warn('env.get_toctree_for() is deprecated. '
'Use sphinx.environment.adapters.toctre.TocTree instead.',
RemovedInSphinx20Warning)
return TocTree(self).get_toctree_for(docname, builder, collapse, **kwds)
def get_domain(self, domainname):
# type: (unicode) -> Domain
"""Return the domain instance with the specified name.
@ -677,16 +625,6 @@ class BuildEnvironment(object):
# allow custom references to be resolved
self.app.emit('doctree-resolved', doctree, docname)
def create_index(self, builder, group_entries=True,
_fixre=re.compile(r'(.*) ([(][^()]*[)])')):
# type: (Builder, bool, Pattern) -> List[Tuple[unicode, List[Tuple[unicode, List[unicode]]]]] # NOQA
warnings.warn('env.create_index() is deprecated. '
'Use sphinx.environment.adapters.indexentreis.IndexEntries instead.',
RemovedInSphinx20Warning)
return IndexEntries(self).create_index(builder,
group_entries=group_entries,
_fixre=_fixre)
def collect_relations(self):
# type: () -> Dict[unicode, List[unicode]]
traversed = set()

View File

@ -14,18 +14,14 @@
import inspect
import re
import sys
import warnings
from typing import Any
from docutils.statemachine import ViewList
from six import iteritems, itervalues, text_type, class_types, string_types
import sphinx
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.errors import ExtensionError
from sphinx.ext.autodoc.importer import mock, import_object, get_object_members
from sphinx.ext.autodoc.importer import _MockImporter # to keep compatibility # NOQA
from sphinx.ext.autodoc.inspector import format_annotation, formatargspec # to keep compatibility # NOQA
from sphinx.locale import _, __
from sphinx.pycode import ModuleAnalyzer, PycodeError
from sphinx.util import logging
@ -110,58 +106,6 @@ def bool_option(arg):
return True
class AutodocReporter(object):
"""
A reporter replacement that assigns the correct source name
and line number to a system message, as recorded in a ViewList.
"""
def __init__(self, viewlist, reporter):
# type: (ViewList, Reporter) -> None
warnings.warn('AutodocReporter is now deprecated. '
'Use sphinx.util.docutils.switch_source_input() instead.',
RemovedInSphinx20Warning)
self.viewlist = viewlist
self.reporter = reporter
def __getattr__(self, name):
# type: (unicode) -> Any
return getattr(self.reporter, name)
def system_message(self, level, message, *children, **kwargs):
# type: (int, unicode, Any, Any) -> nodes.system_message
if 'line' in kwargs and 'source' not in kwargs:
try:
source, line = self.viewlist.items[kwargs['line']]
except IndexError:
pass
else:
kwargs['source'] = source
kwargs['line'] = line
return self.reporter.system_message(level, message,
*children, **kwargs)
def debug(self, *args, **kwargs):
# type: (Any, Any) -> nodes.system_message
if self.reporter.debug_flag:
return self.system_message(0, *args, **kwargs)
def info(self, *args, **kwargs):
# type: (Any, Any) -> nodes.system_message
return self.system_message(1, *args, **kwargs)
def warning(self, *args, **kwargs):
# type: (Any, Any) -> nodes.system_message
return self.system_message(2, *args, **kwargs)
def error(self, *args, **kwargs):
# type: (Any, Any) -> nodes.system_message
return self.system_message(3, *args, **kwargs)
def severe(self, *args, **kwargs):
# type: (Any, Any) -> nodes.system_message
return self.system_message(4, *args, **kwargs)
# Some useful event listener factories for autodoc-process-docstring.
def cut_lines(pre, post=0, what=None):
@ -1452,87 +1396,16 @@ class InstanceAttributeDocumenter(AttributeDocumenter):
AttributeDocumenter.add_content(self, more_content, no_docstring=True)
class DeprecatedDict(dict):
def __init__(self, message):
# type: (str) -> None
self.message = message
super(DeprecatedDict, self).__init__()
def __setitem__(self, key, value):
# type: (unicode, Any) -> None
warnings.warn(self.message, RemovedInSphinx20Warning)
super(DeprecatedDict, self).__setitem__(key, value)
def setdefault(self, key, default=None):
# type: (unicode, Any) -> None
warnings.warn(self.message, RemovedInSphinx20Warning)
super(DeprecatedDict, self).setdefault(key, default)
def update(self, other=None): # type: ignore
# type: (Dict) -> None
warnings.warn(self.message, RemovedInSphinx20Warning)
super(DeprecatedDict, self).update(other)
class AutodocRegistry(object):
"""
A registry of Documenters and attrgetters.
Note: When importing an object, all items along the import chain are
accessed using the descendant's *_special_attrgetters*, thus this
dictionary should include all necessary functions for accessing
attributes of the parents.
"""
# a registry of objtype -> documenter class (Deprecated)
_registry = DeprecatedDict(
'AutoDirective._registry has been deprecated. '
'Please use app.add_autodocumenter() instead.'
) # type: Dict[unicode, Type[Documenter]]
# a registry of type -> getattr function
_special_attrgetters = DeprecatedDict(
'AutoDirective._special_attrgetters has been deprecated. '
'Please use app.add_autodoc_attrgetter() instead.'
) # type: Dict[Type, Callable]
AutoDirective = AutodocRegistry # for backward compatibility
def add_documenter(cls):
# type: (Type[Documenter]) -> None
"""Register a new Documenter."""
warnings.warn('sphinx.ext.autodoc.add_documenter() has been deprecated. '
'Please use app.add_autodocumenter() instead.',
RemovedInSphinx20Warning)
if not issubclass(cls, Documenter):
raise ExtensionError('autodoc documenter %r must be a subclass '
'of Documenter' % cls)
# actually, it should be possible to override Documenters
# if cls.objtype in AutoDirective._registry:
# raise ExtensionError('autodoc documenter for %r is already '
# 'registered' % cls.objtype)
AutoDirective._registry[cls.objtype] = cls
def get_documenters(app):
# type: (Sphinx) -> Dict[unicode, Type[Documenter]]
"""Returns registered Documenter classes"""
classes = dict(AutoDirective._registry) # registered directly
if app:
classes.update(app.registry.documenters) # registered by API
return classes
return app.registry.documenters
def autodoc_attrgetter(app, obj, name, *defargs):
# type: (Sphinx, Any, unicode, Any) -> Any
"""Alternative getattr() for types"""
candidates = dict(AutoDirective._special_attrgetters)
if app:
candidates.update(app.registry.autodoc_attrgettrs)
for typ, func in iteritems(candidates):
for typ, func in iteritems(app.registry.autodoc_attrgettrs):
if isinstance(obj, typ):
return func(obj, name, *defargs)

View File

@ -1,187 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.ext.autodoc.inspector
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Inspect utilities for autodoc
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import typing
import warnings
from six import StringIO, string_types
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.util.inspect import object_description
if False:
# For type annotation
from typing import Any, Callable, Dict, Tuple # NOQA
def format_annotation(annotation):
# type: (Any) -> str
"""Return formatted representation of a type annotation.
Show qualified names for types and additional details for types from
the ``typing`` module.
Displaying complex types from ``typing`` relies on its private API.
"""
warnings.warn('format_annotation() is now deprecated. '
'Please use sphinx.util.inspect.Signature instead.',
RemovedInSphinx20Warning)
if isinstance(annotation, typing.TypeVar): # type: ignore
return annotation.__name__
if annotation == Ellipsis:
return '...'
if not isinstance(annotation, type):
return repr(annotation)
qualified_name = (annotation.__module__ + '.' + annotation.__qualname__ # type: ignore
if annotation else repr(annotation))
if annotation.__module__ == 'builtins':
return annotation.__qualname__ # type: ignore
else:
if hasattr(typing, 'GenericMeta') and \
isinstance(annotation, typing.GenericMeta):
# In Python 3.5.2+, all arguments are stored in __args__,
# whereas __parameters__ only contains generic parameters.
#
# Prior to Python 3.5.2, __args__ is not available, and all
# arguments are in __parameters__.
params = None
if hasattr(annotation, '__args__'):
if annotation.__args__ is None or len(annotation.__args__) <= 2: # type: ignore # NOQA
params = annotation.__args__ # type: ignore
else: # typing.Callable
args = ', '.join(format_annotation(a) for a in annotation.__args__[:-1]) # type: ignore # NOQA
result = format_annotation(annotation.__args__[-1]) # type: ignore
return '%s[[%s], %s]' % (qualified_name, args, result)
elif hasattr(annotation, '__parameters__'):
params = annotation.__parameters__ # type: ignore
if params is not None:
param_str = ', '.join(format_annotation(p) for p in params)
return '%s[%s]' % (qualified_name, param_str)
elif (hasattr(typing, 'UnionMeta') and
isinstance(annotation, typing.UnionMeta) and # type: ignore
hasattr(annotation, '__union_params__')):
params = annotation.__union_params__
if params is not None:
param_str = ', '.join(format_annotation(p) for p in params)
return '%s[%s]' % (qualified_name, param_str)
elif (hasattr(typing, 'CallableMeta') and
isinstance(annotation, typing.CallableMeta) and # type: ignore
getattr(annotation, '__args__', None) is not None and
hasattr(annotation, '__result__')):
# Skipped in the case of plain typing.Callable
args = annotation.__args__
if args is None:
return qualified_name
elif args is Ellipsis:
args_str = '...'
else:
formatted_args = (format_annotation(a) for a in args)
args_str = '[%s]' % ', '.join(formatted_args)
return '%s[%s, %s]' % (qualified_name,
args_str,
format_annotation(annotation.__result__))
elif (hasattr(typing, 'TupleMeta') and
isinstance(annotation, typing.TupleMeta) and # type: ignore
hasattr(annotation, '__tuple_params__') and
hasattr(annotation, '__tuple_use_ellipsis__')):
params = annotation.__tuple_params__
if params is not None:
param_strings = [format_annotation(p) for p in params]
if annotation.__tuple_use_ellipsis__:
param_strings.append('...')
return '%s[%s]' % (qualified_name,
', '.join(param_strings))
return qualified_name
def formatargspec(function, args, varargs=None, varkw=None, defaults=None,
kwonlyargs=(), kwonlydefaults={}, annotations={}):
# type: (Callable, Tuple[str, ...], str, str, Any, Tuple, Dict, Dict[str, Any]) -> str
"""Return a string representation of an ``inspect.FullArgSpec`` tuple.
An enhanced version of ``inspect.formatargspec()`` that handles typing
annotations better.
"""
warnings.warn('formatargspec() is now deprecated. '
'Please use sphinx.util.inspect.Signature instead.',
RemovedInSphinx20Warning)
def format_arg_with_annotation(name):
# type: (str) -> str
if name in annotations:
return '%s: %s' % (name, format_annotation(get_annotation(name)))
return name
def get_annotation(name):
# type: (str) -> str
value = annotations[name]
if isinstance(value, string_types):
return introspected_hints.get(name, value)
else:
return value
try:
introspected_hints = (typing.get_type_hints(function) # type: ignore
if typing and hasattr(function, '__code__') else {})
except Exception:
introspected_hints = {}
fd = StringIO()
fd.write('(')
formatted = []
defaults_start = len(args) - len(defaults) if defaults else len(args)
for i, arg in enumerate(args):
arg_fd = StringIO()
if isinstance(arg, list):
# support tupled arguments list (only for py2): def foo((x, y))
arg_fd.write('(')
arg_fd.write(format_arg_with_annotation(arg[0]))
for param in arg[1:]:
arg_fd.write(', ')
arg_fd.write(format_arg_with_annotation(param))
arg_fd.write(')')
else:
arg_fd.write(format_arg_with_annotation(arg))
if defaults and i >= defaults_start:
arg_fd.write(' = ' if arg in annotations else '=')
arg_fd.write(object_description(defaults[i - defaults_start])) # type: ignore
formatted.append(arg_fd.getvalue())
if varargs:
formatted.append('*' + format_arg_with_annotation(varargs))
if kwonlyargs:
if not varargs:
formatted.append('*')
for kwarg in kwonlyargs:
arg_fd = StringIO()
arg_fd.write(format_arg_with_annotation(kwarg))
if kwonlydefaults and kwarg in kwonlydefaults:
arg_fd.write(' = ' if kwarg in annotations else '=')
arg_fd.write(object_description(kwonlydefaults[kwarg])) # type: ignore
formatted.append(arg_fd.getvalue())
if varkw:
formatted.append('**' + format_arg_with_annotation(varkw))
fd.write(', '.join(formatted))
fd.write(')')
if 'return' in annotations:
fd.write(' -> ')
fd.write(format_annotation(get_annotation('return')))
return fd.getvalue()

View File

@ -58,7 +58,6 @@ import os
import posixpath
import re
import sys
import warnings
from types import ModuleType
from docutils import nodes
@ -70,7 +69,6 @@ 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
@ -175,8 +173,8 @@ class FakeDirective(DocumenterBridge):
super(FakeDirective, self).__init__({}, None, Options(), 0) # type: ignore
def get_documenter(*args):
# type: (Any) -> Type[Documenter]
def get_documenter(app, obj, parent):
# type: (Sphinx, Any, Any) -> Type[Documenter]
"""Get an autodoc.Documenter class suitable for documenting the given
object.
@ -185,16 +183,6 @@ def get_documenter(*args):
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

View File

@ -30,7 +30,6 @@ import functools
import posixpath
import sys
import time
import warnings
from os import path
from docutils import nodes
@ -40,7 +39,6 @@ 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
@ -380,15 +378,6 @@ def setup(app):
}
def debug(argv):
# type: (List[unicode]) -> None
"""Debug functionality to print out an inventory"""
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"""

View File

@ -55,8 +55,6 @@ class Parser(docutils.parsers.Parser):
self.app = app
self.config = app.config
self.env = app.env
self.warn = app.warn
self.info = app.info
class RSTParser(docutils.parsers.rst.Parser):

View File

@ -1,41 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.quickstart
~~~~~~~~~~~~~~~~~
This file has moved to :py:mod:`sphinx.cmd.quickstart`.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import warnings
from sphinx.cmd.quickstart import main as _main
from sphinx.deprecation import RemovedInSphinx20Warning
if False:
# For type annotation
from typing import Any # NOQA
def main(*args, **kwargs):
# type: (Any, Any) -> None
warnings.warn(
'`sphinx.quickstart.main()` has moved to `sphinx.cmd.quickstart.'
'main()`.',
RemovedInSphinx20Warning,
stacklevel=2,
)
args = args[1:] # skip first argument to adjust arguments (refs: #4615)
_main(*args, **kwargs)
# So program can be started with "python -m sphinx.quickstart ..."
if __name__ == "__main__":
warnings.warn(
'`sphinx.quickstart` has moved to `sphinx.cmd.quickstart`.',
RemovedInSphinx20Warning,
stacklevel=2,
)
main()

View File

@ -20,7 +20,6 @@ from six import string_types
from sphinx import application, locale
from sphinx.builders.latex import LaTeXBuilder
from sphinx.ext.autodoc import AutoDirective
from sphinx.pycode import ModuleAnalyzer
from sphinx.testing.path import path
from sphinx.util.osutil import relpath
@ -146,7 +145,6 @@ class SphinxTestApp(application.Sphinx):
def cleanup(self, doctrees=False):
# type: (bool) -> None
AutoDirective._registry.clear()
ModuleAnalyzer.cache.clear()
LaTeXBuilder.usepackages = []
locale.translators.clear()

View File

@ -12,16 +12,14 @@
import os
import shutil
import tempfile
import warnings
from os import path
from zipfile import ZipFile
import pkg_resources
from six import string_types, iteritems
from six import iteritems
from six.moves import configparser
from sphinx import package_dir
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.errors import ThemeError
from sphinx.locale import __
from sphinx.util import logging
@ -229,25 +227,6 @@ class HTMLThemeFactory(object):
except StopIteration:
pass
# look up for old styled entry_points
for entry_point in pkg_resources.iter_entry_points('sphinx_themes'):
target = entry_point.load()
if callable(target):
themedir = target()
if not isinstance(themedir, string_types):
logger.warning(__('Theme extension %r does not respond correctly.') %
entry_point.module_name)
else:
themedir = target
themes = self.find_themes(themedir)
for entry, theme in iteritems(themes):
if name == entry:
warnings.warn('``sphinx_themes`` entry point is now deprecated. '
'Please use ``sphinx.html_themes`` instead.',
RemovedInSphinx20Warning)
self.themes[name] = theme
def find_themes(self, theme_path):
# type: (unicode) -> Dict[unicode, unicode]
"""Search themes from specified directory."""

View File

@ -9,13 +9,9 @@
:license: BSD, see LICENSE for details.
"""
import warnings
from docutils import nodes
from docutils.utils import get_source_line
from sphinx import addnodes
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.environment import NoUri
from sphinx.locale import __
from sphinx.transforms import SphinxTransform
@ -32,35 +28,6 @@ if False:
logger = logging.getLogger(__name__)
class DocReferenceMigrator(SphinxTransform):
"""Migrate :doc: reference to std domain."""
default_priority = 5 # before ReferencesResolver
def apply(self):
# type: () -> None
for node in self.document.traverse(addnodes.pending_xref):
if node.get('reftype') == 'doc' and node.get('refdomain') is None:
source, line = get_source_line(node)
if source and line:
location = "%s:%s" % (source, line)
elif source:
location = "%s:" % source
elif line:
location = "<unknown>:%s" % line
else:
location = None
message = ('Invalid pendig_xref node detected. '
':doc: reference should have refdomain=std attribute.')
if location:
warnings.warn("%s: %s" % (location, message),
RemovedInSphinx20Warning)
else:
warnings.warn(message, RemovedInSphinx20Warning)
node['refdomain'] = 'std'
class ReferencesResolver(SphinxTransform):
"""
Resolves cross-references on doctrees.
@ -191,7 +158,6 @@ class OnlyNodeTransform(SphinxTransform):
def setup(app):
# type: (Sphinx) -> Dict[unicode, Any]
app.add_post_transform(DocReferenceMigrator)
app.add_post_transform(ReferencesResolver)
app.add_post_transform(OnlyNodeTransform)

View File

@ -1,28 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.websupport
~~~~~~~~~~~~~~~~~
Base Module for web support functions.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import warnings
from sphinx.deprecation import RemovedInSphinx20Warning
try:
from sphinxcontrib.websupport import WebSupport # NOQA
from sphinxcontrib.websupport import errors # NOQA
from sphinxcontrib.websupport.search import BaseSearch, SEARCH_ADAPTERS # NOQA
from sphinxcontrib.websupport.storage import StorageBackend # NOQA
warnings.warn('sphinx.websupport module is now provided as sphinxcontrib-websupport. '
'sphinx.websupport will be removed at Sphinx-2.0. '
'Please use the package instead.',
RemovedInSphinx20Warning)
except ImportError:
warnings.warn('Since Sphinx-1.6, sphinx.websupport module is now separated to '
'sphinxcontrib-websupport package. Please add it into your dependency list.')

View File

@ -1,12 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.websupport.errors
~~~~~~~~~~~~~~~~~~~~~~~~
Contains Error classes for the web support package.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinxcontrib.websupport.errors import * # NOQA

View File

@ -1,12 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.websupport.search
~~~~~~~~~~~~~~~~~~~~~~~~
Server side search support for the web support package.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinxcontrib.websupport.search import BaseSearch, SEARCH_ADAPTERS # NOQA

View File

@ -1,12 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.websupport.search.nullsearch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The default search adapter, does nothing.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinxcontrib.websupport.search.nullsearch import NullSearch # NOQA

View File

@ -1,12 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.websupport.search.whooshsearch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Whoosh search adapter.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinxcontrib.websupport.search.whooshsearch import WhooshSearch # NOQA

View File

@ -1,12 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.websupport.search.xapiansearch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xapian search adapter.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinxcontrib.websupport.search.xapiansearch import XapianSearch # NOQA

View File

@ -1,12 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.websupport.storage
~~~~~~~~~~~~~~~~~~~~~~~~~
Storage for the websupport package.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinxcontrib.websupport.storage import StorageBackend # NOQA

View File

@ -1,12 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.websupport.storage.differ
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A differ for creating an HTML representations of proposal diffs
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinxcontrib.websupport.storage.differ import CombinedHtmlDiff # NOQA

View File

@ -1,13 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.websupport.storage.sqlalchemy_db
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SQLAlchemy table and mapper definitions used by the
:class:`sphinx.websupport.storage.sqlalchemystorage.SQLAlchemyStorage`.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinxcontrib.websupport.storage.sqlalchemy_db import Node, Comment, CommentVote # NOQA

View File

@ -1,12 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.websupport.storage.sqlalchemystorage
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An SQLAlchemy storage backend.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinxcontrib.websupport.storage.sqlalchemystorage import SQLAlchemyStorage # NOQA

View File

@ -18,9 +18,10 @@ import six
from docutils.statemachine import ViewList
from six import StringIO
from sphinx.ext.autodoc import add_documenter, FunctionDocumenter, ALL # NOQA
from sphinx.ext.autodoc import FunctionDocumenter, ALL
from sphinx.testing.util import SphinxTestApp, Struct
from sphinx.util import logging
from sphinx.util import save_traceback # NOQA
app = None
@ -181,7 +182,7 @@ def test_generate():
'Class.meth', more_content=add_content)
# test check_module
inst = FunctionDocumenter(directive, 'add_documenter')
inst = FunctionDocumenter(directive, 'save_traceback')
inst.generate(check_module=True)
assert len(directive.result) == 0

View File

@ -11,7 +11,6 @@ from sphinx.writers.latex import LaTeXTranslator
from sphinx.writers.manpage import ManualPageTranslator
from sphinx.writers.texinfo import TexinfoTranslator
from sphinx.writers.text import TextTranslator
from sphinx.writers.websupport import WebSupportTranslator
project = 'test'
@ -54,10 +53,6 @@ class ConfTextTranslator(TextTranslator):
pass
class ConfWebSupportTranslator(WebSupportTranslator):
pass
class ConfXMLTranslator(XMLTranslator):
pass
@ -76,6 +71,5 @@ def setup(app):
app.set_translator('man', ConfManualPageTranslator)
app.set_translator('texinfo', ConfTexinfoTranslator)
app.set_translator('text', ConfTextTranslator)
app.set_translator('websupport', ConfWebSupportTranslator)
app.set_translator('xml', ConfXMLTranslator)
app.set_translator('pseudoxml', ConfPseudoXMLTranslator)

View File

@ -4,7 +4,7 @@ import enum
from six import StringIO, add_metaclass
from sphinx.ext.autodoc import add_documenter # NOQA
from sphinx.util import save_traceback # NOQA
__all__ = ['Class']

View File

@ -4,8 +4,6 @@ import enum
from six import StringIO, add_metaclass
from sphinx.ext.autodoc import add_documenter # NOQA
__all__ = ['Class']

View File

@ -20,7 +20,7 @@ from docutils.statemachine import ViewList
from six import PY3
from sphinx.ext.autodoc import (
AutoDirective, ModuleLevelDocumenter, cut_lines, between, ALL,
ModuleLevelDocumenter, cut_lines, between, ALL,
merge_autodoc_default_flags
)
from sphinx.ext.autodoc.directive import DocumenterBridge, process_documenter_options
@ -112,7 +112,7 @@ def setup_test():
yield
AutoDirective._special_attrgetters.clear()
app.registry.autodoc_attrgettrs.clear()
processed_docstrings = []
@ -566,7 +566,7 @@ def test_attrgetter_using():
getattr_spy.append((obj, name))
return None
return getattr(obj, name, *defargs)
AutoDirective._special_attrgetters[type] = special_getattr
app.add_autodoc_attrgetter(type, special_getattr)
del getattr_spy[:]
inst = app.registry.documenters[objtype](directive, name)
@ -752,7 +752,7 @@ def test_autodoc_imported_members(app):
"imported-members": None,
"ignore-module-all": None}
actual = do_autodoc(app, 'module', 'target', options)
assert '.. py:function:: add_documenter(cls)' in actual
assert '.. py:function:: save_traceback(app)' in actual
@pytest.mark.sphinx('html', testroot='ext-autodoc')

View File

@ -1,36 +0,0 @@
# -*- coding: utf-8 -*-
"""
test_websupport
~~~~~~~~~~~~~~~
Test the Web Support Package
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import pytest
from sphinx.websupport import WebSupport
try:
sqlalchemy_missing = False
import sqlalchemy # NOQA
except ImportError:
sqlalchemy_missing = True
@pytest.mark.skipif(sqlalchemy_missing, reason='needs sqlalchemy')
def test_build(request, rootdir, sphinx_test_tempdir):
settings = {
'srcdir': rootdir / 'test-basic',
# to use same directory for 'builddir' in each 'support' fixture, using
# 'sphinx_test_tempdir' (static) value instead of 'tempdir' fixture value.
# each test expect result of db value at previous test case.
'builddir': sphinx_test_tempdir / 'websupport'
}
marker = request.node.get_marker('support')
if marker:
settings.update(marker.kwargs)
support = WebSupport(**settings)
support.build()

View File

@ -65,5 +65,7 @@ commands=
basepython = python3
description =
Build documentation.
deps =
sphinxcontrib-websupport
commands =
python setup.py build_sphinx {posargs}