summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTakeshi KOMIYA <i.tkomiya@gmail.com>2019-03-29 23:52:32 +0900
committerTakeshi KOMIYA <i.tkomiya@gmail.com>2019-03-30 14:50:37 +0900
commit61098a0ae2e696a804459d36bd74ca57db76eda5 (patch)
tree2d71c39d199fec7366a013e0b48c1b2fb4bc83ee
parentc1a254f2491436ac304f1f169aa488438abe4193 (diff)
downloadsphinx-git-61098a0ae2e696a804459d36bd74ca57db76eda5.tar.gz
Drop features and APIs deprecated in 1.8
-rw-r--r--CHANGES2
-rw-r--r--doc/extdev/appapi.rst2
-rw-r--r--sphinx/addnodes.py56
-rw-r--r--sphinx/application.py97
-rw-r--r--sphinx/builders/html.py49
-rw-r--r--sphinx/builders/latex/util.py11
-rw-r--r--sphinx/cmdline.py49
-rw-r--r--sphinx/config.py37
-rw-r--r--sphinx/deprecation.py6
-rw-r--r--sphinx/domains/changeset.py9
-rw-r--r--sphinx/domains/math.py2
-rw-r--r--sphinx/domains/python.py10
-rw-r--r--sphinx/domains/std.py13
-rw-r--r--sphinx/environment/__init__.py135
-rw-r--r--sphinx/ext/autodoc/__init__.py39
-rw-r--r--sphinx/ext/autodoc/importer.py3
-rw-r--r--sphinx/ext/autodoc/mock.py52
-rw-r--r--sphinx/ext/mathbase.py84
-rw-r--r--sphinx/ext/viewcode.py10
-rw-r--r--sphinx/highlighting.py33
-rw-r--r--sphinx/io.py102
-rw-r--r--sphinx/locale/__init__.py29
-rw-r--r--sphinx/make_mode.py38
-rw-r--r--sphinx/registry.py66
-rw-r--r--sphinx/search/ja.py16
-rw-r--r--sphinx/transforms/post_transforms/compat.py90
-rw-r--r--sphinx/util/__init__.py37
-rw-r--r--sphinx/util/compat.py16
-rw-r--r--sphinx/util/docutils.py26
-rw-r--r--sphinx/util/i18n.py12
-rw-r--r--sphinx/util/images.py14
-rw-r--r--sphinx/util/inspect.py22
-rw-r--r--sphinx/util/osutil.py25
-rw-r--r--sphinx/versioning.py11
-rw-r--r--sphinx/writers/html.py33
-rw-r--r--sphinx/writers/html5.py33
-rw-r--r--sphinx/writers/latex.py130
-rw-r--r--sphinx/writers/texinfo.py12
-rw-r--r--sphinx/writers/text.py12
-rw-r--r--tests/roots/test-add_source_parser/conf.py11
-rw-r--r--tests/roots/test-ext-math-compat/conf.py9
-rw-r--r--tests/test_application.py9
-rw-r--r--tests/test_autodoc.py26
-rw-r--r--tests/test_ext_autodoc_mock.py2
-rw-r--r--tests/test_util_images.py38
45 files changed, 73 insertions, 1445 deletions
diff --git a/CHANGES b/CHANGES
index 934c553e3..33cc8ccf7 100644
--- a/CHANGES
+++ b/CHANGES
@@ -7,6 +7,8 @@ Dependencies
Incompatible changes
--------------------
+* Drop features and APIs deprecated in 1.8.x
+
Deprecated
----------
diff --git a/doc/extdev/appapi.rst b/doc/extdev/appapi.rst
index fe64628a4..4cb8501be 100644
--- a/doc/extdev/appapi.rst
+++ b/doc/extdev/appapi.rst
@@ -54,8 +54,6 @@ package.
.. automethod:: Sphinx.add_domain(domain)
-.. automethod:: Sphinx.override_domain(domain)
-
.. method:: Sphinx.add_directive_to_domain(domain, name, func, content, arguments, \*\*options)
.. automethod:: Sphinx.add_directive_to_domain(domain, name, directiveclass)
diff --git a/sphinx/addnodes.py b/sphinx/addnodes.py
index ef3bf3f9e..4180625ca 100644
--- a/sphinx/addnodes.py
+++ b/sphinx/addnodes.py
@@ -12,7 +12,7 @@ import warnings
from docutils import nodes
-from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
+from sphinx.deprecation import RemovedInSphinx40Warning
if False:
# For type annotation
@@ -188,59 +188,6 @@ class production(nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for a single grammar production rule."""
-# math nodes
-
-
-class math(nodes.math):
- """Node for inline equations.
-
- .. warning:: This node is provided to keep compatibility only.
- It will be removed in nearly future. Don't use this from your extension.
-
- .. deprecated:: 1.8
- Use ``docutils.nodes.math`` instead.
- """
-
- def __getitem__(self, key):
- """Special accessor for supporting ``node['latex']``."""
- if key == 'latex' and 'latex' not in self.attributes:
- warnings.warn("math node for Sphinx was replaced by docutils'. "
- "Therefore please use ``node.astext()`` to get an equation instead.",
- RemovedInSphinx30Warning, stacklevel=2)
- return self.astext()
- else:
- return super().__getitem__(key)
-
-
-class math_block(nodes.math_block):
- """Node for block level equations.
-
- .. warning:: This node is provided to keep compatibility only.
- It will be removed in nearly future. Don't use this from your extension.
-
- .. deprecated:: 1.8
- """
-
- def __getitem__(self, key):
- if key == 'latex' and 'latex' not in self.attributes:
- warnings.warn("displaymath node for Sphinx was replaced by docutils'. "
- "Therefore please use ``node.astext()`` to get an equation instead.",
- RemovedInSphinx30Warning, stacklevel=2)
- return self.astext()
- else:
- return super().__getitem__(key)
-
-
-class displaymath(math_block):
- """Node for block level equations.
-
- .. warning:: This node is provided to keep compatibility only.
- It will be removed in nearly future. Don't use this from your extension.
-
- .. deprecated:: 1.8
- """
-
-
# other directive-level nodes
class index(nodes.Invisible, nodes.Inline, nodes.TextElement):
@@ -379,7 +326,6 @@ def setup(app):
app.add_node(seealso)
app.add_node(productionlist)
app.add_node(production)
- app.add_node(displaymath)
app.add_node(index)
app.add_node(centered)
app.add_node(acks)
diff --git a/sphinx/application.py b/sphinx/application.py
index aee9f4410..516b7be58 100644
--- a/sphinx/application.py
+++ b/sphinx/application.py
@@ -15,7 +15,6 @@ import pickle
import sys
import warnings
from collections import deque
-from inspect import isclass
from io import StringIO
from os import path
@@ -25,9 +24,7 @@ import sphinx
from sphinx import package_dir, locale
from sphinx.config import Config
from sphinx.config import CONFIG_FILENAME # NOQA # for compatibility (RemovedInSphinx30)
-from sphinx.deprecation import (
- RemovedInSphinx30Warning, RemovedInSphinx40Warning
-)
+from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.environment import BuildEnvironment
from sphinx.errors import ApplicationError, ConfigError, VersionRequirementError
from sphinx.events import EventManager
@@ -35,11 +32,10 @@ from sphinx.locale import __
from sphinx.project import Project
from sphinx.registry import SphinxComponentRegistry
from sphinx.util import docutils
-from sphinx.util import import_object, progress_message
from sphinx.util import logging
+from sphinx.util import progress_message
from sphinx.util.build_phase import BuildPhase
from sphinx.util.console import bold # type: ignore
-from sphinx.util.docutils import directive_helper
from sphinx.util.i18n import CatalogRepository
from sphinx.util.logging import prefixed_warnings
from sphinx.util.osutil import abspath, ensuredir, relpath
@@ -98,7 +94,6 @@ builtin_extensions = (
'sphinx.transforms.post_transforms',
'sphinx.transforms.post_transforms.code',
'sphinx.transforms.post_transforms.images',
- 'sphinx.transforms.post_transforms.compat',
'sphinx.util.compat',
'sphinx.versioning',
# collectors should be loaded by specific order
@@ -397,18 +392,6 @@ class Sphinx:
if version > sphinx.__display_version__[:3]:
raise VersionRequirementError(version)
- def import_object(self, objname, source=None):
- # type: (str, str) -> Any
- """Import an object from a ``module.name`` string.
-
- .. deprecated:: 1.8
- Use ``sphinx.util.import_object()`` instead.
- """
- warnings.warn('app.import_object() is deprecated. '
- 'Use sphinx.util.add_object_type() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return import_object(objname, source=None)
-
# event interface
def connect(self, event, callback):
# type: (str, Callable) -> int
@@ -593,36 +576,14 @@ class Sphinx:
self.registry.add_enumerable_node(node, figtype, title_getter, override=override)
self.add_node(node, override=override, **kwds)
- @property
- def enumerable_nodes(self):
- # type: () -> Dict[Type[nodes.Node], Tuple[str, TitleGetter]]
- warnings.warn('app.enumerable_nodes() is deprecated. '
- 'Use app.get_domain("std").enumerable_nodes instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.registry.enumerable_nodes
-
- def add_directive(self, name, obj, content=None, arguments=None, override=False, **options): # NOQA
- # type: (str, Any, bool, Tuple[int, int, bool], bool, Any) -> None
+ def add_directive(self, name, cls, override=False):
+ # type: (str, Type[Directive], bool) -> None
"""Register a Docutils directive.
- *name* must be the prospective directive name. There are two possible
- ways to write a directive:
-
- - In the docutils 0.4 style, *obj* is the directive function.
- *content*, *arguments* and *options* are set as attributes on the
- function and determine whether the directive has content, arguments
- and options, respectively. **This style is deprecated.**
-
- - In the docutils 0.5 style, *obj* is the directive class.
- It must already have attributes named *has_content*,
- *required_arguments*, *optional_arguments*,
- *final_argument_whitespace* and *option_spec* that correspond to the
- options for the function way. See `the Docutils docs
- <http://docutils.sourceforge.net/docs/howto/rst-directives.html>`_
- for details.
-
- The directive class must inherit from the class
- ``docutils.parsers.rst.Directive``.
+ *name* must be the prospective directive name. *cls* is a directive
+ class which inherits ``docutils.parsers.rst.Directive``. For more
+ details, see `the Docutils docs
+ <http://docutils.sourceforge.net/docs/howto/rst-directives.html>`_ .
For example, the (already existing) :rst:dir:`literalinclude` directive
would be added like this:
@@ -653,17 +614,12 @@ class Sphinx:
.. versionchanged:: 1.8
Add *override* keyword.
"""
- logger.debug('[app] adding directive: %r',
- (name, obj, content, arguments, options))
+ logger.debug('[app] adding directive: %r', (name, cls))
if not override and docutils.is_directive_registered(name):
logger.warning(__('directive %r is already registered, it will be overridden'),
name, type='app', subtype='add_directive')
- if not isclass(obj) or not issubclass(obj, Directive):
- directive = directive_helper(obj, content, arguments, **options)
- docutils.register_directive(name, directive)
- else:
- docutils.register_directive(name, obj)
+ docutils.register_directive(name, cls)
def add_role(self, name, role, override=False):
# type: (str, Any, bool) -> None
@@ -716,26 +672,8 @@ class Sphinx:
"""
self.registry.add_domain(domain, override=override)
- def override_domain(self, domain):
- # type: (Type[Domain]) -> None
- """Override a registered domain.
-
- Make the given *domain* class known to Sphinx, assuming that there is
- already a domain with its ``.name``. The new domain must be a subclass
- of the existing one.
-
- .. versionadded:: 1.0
- .. deprecated:: 1.8
- Integrated to :meth:`add_domain`.
- """
- warnings.warn('app.override_domain() is deprecated. '
- 'Use app.add_domain() with override option instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- self.registry.add_domain(domain, override=True)
-
- def add_directive_to_domain(self, domain, name, obj, has_content=None, argument_spec=None,
- override=False, **option_spec):
- # type: (str, str, Any, bool, Any, bool, Any) -> None
+ def add_directive_to_domain(self, domain, name, cls, override=False):
+ # type: (str, str, Type[Directive], bool) -> None
"""Register a Docutils directive in a domain.
Like :meth:`add_directive`, but the directive is added to the domain
@@ -745,9 +683,7 @@ class Sphinx:
.. versionchanged:: 1.8
Add *override* keyword.
"""
- self.registry.add_directive_to_domain(domain, name, obj,
- has_content, argument_spec, override=override,
- **option_spec)
+ self.registry.add_directive_to_domain(domain, name, cls, override=override)
def add_role_to_domain(self, domain, name, role, override=False):
# type: (str, str, Union[RoleFunction, XRefRole], bool) -> None
@@ -1205,13 +1141,6 @@ class Sphinx:
return True
- @property
- def _setting_up_extension(self):
- # type: () -> List[str]
- warnings.warn('app._setting_up_extension is deprecated.',
- RemovedInSphinx30Warning)
- return ['?']
-
class TemplateBridge:
"""
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index 3f167d0d3..5621f9a75 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -24,9 +24,7 @@ from docutils.utils import relative_path
from sphinx import package_dir, __display_version__
from sphinx.builders import Builder
-from sphinx.deprecation import (
- RemovedInSphinx30Warning, RemovedInSphinx40Warning, deprecated_alias
-)
+from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.environment.adapters.asset import ImageAdapter
from sphinx.environment.adapters.indexentries import IndexEntries
from sphinx.environment.adapters.toctree import TocTree
@@ -105,39 +103,6 @@ class Stylesheet(str):
return self
-class JSContainer(list):
- """The container for JavaScript scripts."""
- def insert(self, index, obj):
- # type: (int, str) -> None
- warnings.warn('To modify script_files in the theme is deprecated. '
- 'Please insert a <script> tag directly in your theme instead.',
- RemovedInSphinx30Warning, stacklevel=3)
- super().insert(index, obj)
-
- def extend(self, other): # type: ignore
- # type: (List[str]) -> None
- warnings.warn('To modify script_files in the theme is deprecated. '
- 'Please insert a <script> tag directly in your theme instead.',
- RemovedInSphinx30Warning, stacklevel=3)
- for item in other:
- self.append(item)
-
- def __iadd__(self, other): # type: ignore
- # type: (List[str]) -> JSContainer
- warnings.warn('To modify script_files in the theme is deprecated. '
- 'Please insert a <script> tag directly in your theme instead.',
- RemovedInSphinx30Warning, stacklevel=3)
- for item in other:
- self.append(item)
- return self
-
- def __add__(self, other):
- # type: (List[str]) -> JSContainer
- ret = JSContainer(self)
- ret += other
- return ret
-
-
class JavaScript(str):
"""A metadata of javascript file.
@@ -247,7 +212,7 @@ class StandaloneHTMLBuilder(Builder):
self.css_files = [] # type: List[Dict[str, str]]
# JS files
- self.script_files = JSContainer() # type: List[JavaScript]
+ self.script_files = [] # type: List[JavaScript]
def init(self):
# type: () -> None
@@ -1068,16 +1033,6 @@ class StandaloneHTMLBuilder(Builder):
return False
ctx['hasdoc'] = hasdoc
- def warn(*args, **kwargs):
- # type: (Any, Any) -> str
- """Simple warn() wrapper for themes."""
- warnings.warn('The template function warn() was deprecated. '
- 'Use warning() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- logger.warning(*args, **kwargs)
- return '' # return empty string
- ctx['warn'] = warn
-
ctx['toctree'] = lambda **kw: self._get_local_toctree(pagename, **kw)
self.add_sidebars(pagename, ctx)
ctx.update(addctx)
diff --git a/sphinx/builders/latex/util.py b/sphinx/builders/latex/util.py
index 156ea89ad..1765cb0ce 100644
--- a/sphinx/builders/latex/util.py
+++ b/sphinx/builders/latex/util.py
@@ -8,12 +8,8 @@
:license: BSD, see LICENSE for details.
"""
-import warnings
-
from docutils.writers.latex2e import Babel
-from sphinx.deprecation import RemovedInSphinx30Warning
-
class ExtBabel(Babel):
cyrillic_languages = ('bulgarian', 'kazakh', 'mongolian', 'russian', 'ukrainian')
@@ -25,13 +21,6 @@ class ExtBabel(Babel):
self.supported = True
super().__init__(language_code or '')
- def get_shorthandoff(self):
- # type: () -> str
- warnings.warn('ExtBabel.get_shorthandoff() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- from sphinx.writers.latex import SHORTHANDOFF
- return SHORTHANDOFF
-
def uses_cyrillic(self):
# type: () -> bool
return self.language in self.cyrillic_languages
diff --git a/sphinx/cmdline.py b/sphinx/cmdline.py
deleted file mode 100644
index 5247eb157..000000000
--- a/sphinx/cmdline.py
+++ /dev/null
@@ -1,49 +0,0 @@
-"""
- sphinx.cmdline
- ~~~~~~~~~~~~~~
-
- sphinx-build command-line handling.
-
- :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import sys
-import warnings
-
-from sphinx.cmd import build
-from sphinx.deprecation import RemovedInSphinx30Warning
-
-if False:
- # For type annotation
- import argparse # NOQA
- from typing import Any, IO, List, Union # NOQA
- from sphinx.application import Sphinx # NOQA
-
-
-def handle_exception(app, args, exception, stderr=sys.stderr):
- # type: (Sphinx, Any, Union[Exception, KeyboardInterrupt], IO) -> None
- warnings.warn('sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- build.handle_exception(app, args, exception, stderr)
-
-
-def jobs_argument(value):
- # type: (str) -> int
- warnings.warn('sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return build.jobs_argument(value)
-
-
-def get_parser():
- # type: () -> argparse.ArgumentParser
- warnings.warn('sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return build.get_parser()
-
-
-def main(argv=sys.argv[1:]):
- # type: (List[str]) -> int
- warnings.warn('sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return build.main(argv)
diff --git a/sphinx/config.py b/sphinx/config.py
index 5ba2c2a3d..06718eb2b 100644
--- a/sphinx/config.py
+++ b/sphinx/config.py
@@ -16,7 +16,7 @@ from collections import OrderedDict
from os import path, getenv
from typing import Any, NamedTuple, Union
-from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
+from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.errors import ConfigError, ExtensionError
from sphinx.locale import _, __
from sphinx.util import logging
@@ -155,27 +155,8 @@ class Config:
'env', []),
} # type: Dict[str, Tuple]
- def __init__(self, *args):
- # type: (Any) -> None
- if len(args) == 4:
- # old style arguments: (dirname, filename, overrides, tags)
- warnings.warn('The argument of Config() class has been changed. '
- 'Use Config.read() to read configuration from conf.py.',
- RemovedInSphinx30Warning, stacklevel=2)
- dirname, filename, overrides, tags = args
- if dirname is None:
- config = {} # type: Dict[str, Any]
- else:
- config = eval_config_file(path.join(dirname, filename), tags)
- else:
- # new style arguments: (config={}, overrides={})
- if len(args) == 0:
- config, overrides = {}, {}
- elif len(args) == 1:
- config, overrides = args[0], {}
- else:
- config, overrides = args[:2]
-
+ def __init__(self, config={}, overrides={}):
+ # type: (Dict[str, Any], Dict[str, Any]) -> None
self.overrides = overrides
self.values = Config.config_values.copy()
self._raw_config = config
@@ -196,18 +177,6 @@ class Config:
namespace = eval_config_file(filename, tags)
return cls(namespace, overrides or {})
- def check_types(self):
- # type: () -> None
- warnings.warn('Config.check_types() is deprecated. Use check_confval_types() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- check_confval_types(None, self)
-
- def check_unicode(self):
- # type: () -> None
- warnings.warn('Config.check_unicode() is deprecated. Use check_unicode() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- check_unicode(self)
-
def convert_overrides(self, name, value):
# type: (str, Any) -> Any
if not isinstance(value, str):
diff --git a/sphinx/deprecation.py b/sphinx/deprecation.py
index 6cdd22ec1..1169280d0 100644
--- a/sphinx/deprecation.py
+++ b/sphinx/deprecation.py
@@ -17,15 +17,11 @@ if False:
from typing import Any, Dict, Type # NOQA
-class RemovedInSphinx30Warning(PendingDeprecationWarning):
- pass
-
-
class RemovedInSphinx40Warning(PendingDeprecationWarning):
pass
-RemovedInNextVersionWarning = RemovedInSphinx30Warning
+RemovedInNextVersionWarning = RemovedInSphinx40Warning
def deprecated_alias(modname, objects, warning):
diff --git a/sphinx/domains/changeset.py b/sphinx/domains/changeset.py
index aeea645c1..d731fe183 100644
--- a/sphinx/domains/changeset.py
+++ b/sphinx/domains/changeset.py
@@ -14,8 +14,6 @@ from typing import cast
from docutils import nodes
from sphinx import addnodes
-from sphinx import locale
-from sphinx.deprecation import DeprecatedDict, RemovedInSphinx30Warning
from sphinx.domains import Domain
from sphinx.locale import _
from sphinx.util.docutils import SphinxDirective
@@ -40,13 +38,6 @@ versionlabel_classes = {
'deprecated': 'deprecated',
}
-locale.versionlabels = DeprecatedDict(
- versionlabels,
- 'sphinx.locale.versionlabels is deprecated. '
- 'Please use sphinx.domains.changeset.versionlabels instead.',
- RemovedInSphinx30Warning
-)
-
# TODO: move to typing.NamedTuple after dropping py35 support (see #5958)
ChangeSet = namedtuple('ChangeSet',
diff --git a/sphinx/domains/math.py b/sphinx/domains/math.py
index bc0ef8328..be5838794 100644
--- a/sphinx/domains/math.py
+++ b/sphinx/domains/math.py
@@ -11,7 +11,6 @@
from docutils import nodes
from docutils.nodes import make_id
-from sphinx.addnodes import math_block as displaymath
from sphinx.domains import Domain
from sphinx.locale import __
from sphinx.roles import XRefRole
@@ -49,7 +48,6 @@ class MathDomain(Domain):
'eq': 'equation not found: %(target)s',
}
enumerable_nodes = { # node_class -> (figtype, title_getter)
- displaymath: ('displaymath', None),
nodes.math_block: ('displaymath', None),
}
roles = {
diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py
index ea71aa976..2203ee6e3 100644
--- a/sphinx/domains/python.py
+++ b/sphinx/domains/python.py
@@ -13,8 +13,7 @@ import re
from docutils import nodes
from docutils.parsers.rst import directives
-from sphinx import addnodes, locale
-from sphinx.deprecation import DeprecatedDict, RemovedInSphinx30Warning
+from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType, Index, IndexEntry
from sphinx.locale import _, __
@@ -55,13 +54,6 @@ pairindextypes = {
'builtin': _('built-in function'),
}
-locale.pairindextypes = DeprecatedDict(
- pairindextypes,
- 'sphinx.locale.pairindextypes is deprecated. '
- 'Please use sphinx.domains.python.pairindextypes instead.',
- RemovedInSphinx30Warning
-)
-
def _pseudo_parse_arglist(signode, arglist):
# type: (addnodes.desc_signature, str) -> None
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index 04e8219c4..e73c660e6 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -10,7 +10,6 @@
import re
import unicodedata
-import warnings
from copy import copy
from typing import cast
@@ -19,7 +18,6 @@ from docutils.parsers.rst import directives
from docutils.statemachine import StringList
from sphinx import addnodes
-from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType
from sphinx.errors import NoUri
@@ -957,17 +955,6 @@ class StandardDomain(Domain):
figtype, _ = self.enumerable_nodes.get(node.__class__, (None, None))
return figtype
- def get_figtype(self, node):
- # type: (nodes.Node) -> str
- """Get figure type of nodes.
-
- .. deprecated:: 1.8
- """
- warnings.warn('StandardDomain.get_figtype() is deprecated. '
- 'Please use get_enumerable_node_type() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.get_enumerable_node_type(node)
-
def get_fignumber(self, env, builder, figtype, docname, target_node):
# type: (BuildEnvironment, Builder, str, str, nodes.Element) -> Tuple[int, ...]
if figtype == 'section':
diff --git a/sphinx/environment/__init__.py b/sphinx/environment/__init__.py
index e3d2c1f49..f931b3b13 100644
--- a/sphinx/environment/__init__.py
+++ b/sphinx/environment/__init__.py
@@ -13,13 +13,10 @@ import pickle
import warnings
from collections import defaultdict
from copy import copy
-from io import BytesIO
from os import path
from sphinx import addnodes
-from sphinx.deprecation import (
- RemovedInSphinx30Warning, RemovedInSphinx40Warning, deprecated_alias
-)
+from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.environment.adapters.toctree import TocTree
from sphinx.errors import SphinxError, BuildEnvironmentError, DocumentError, ExtensionError
from sphinx.locale import __
@@ -657,133 +654,3 @@ class BuildEnvironment:
for domain in self.domains.values():
domain.check_consistency()
self.app.emit('env-check-consistency', self)
-
- # --------- METHODS FOR COMPATIBILITY --------------------------------------
-
- def update(self, config, srcdir, doctreedir):
- # type: (Config, str, str) -> List[str]
- warnings.warn('env.update() is deprecated. Please use builder.read() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.app.builder.read()
-
- def _read_serial(self, docnames, app):
- # type: (List[str], Sphinx) -> None
- warnings.warn('env._read_serial() is deprecated. Please use builder.read() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.app.builder._read_serial(docnames)
-
- def _read_parallel(self, docnames, app, nproc):
- # type: (List[str], Sphinx, int) -> None
- warnings.warn('env._read_parallel() is deprecated. Please use builder.read() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.app.builder._read_parallel(docnames, nproc)
-
- def read_doc(self, docname, app=None):
- # type: (str, Sphinx) -> None
- warnings.warn('env.read_doc() is deprecated. Please use builder.read_doc() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- self.app.builder.read_doc(docname)
-
- def write_doctree(self, docname, doctree):
- # type: (str, nodes.document) -> None
- warnings.warn('env.write_doctree() is deprecated. '
- 'Please use builder.write_doctree() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- self.app.builder.write_doctree(docname, doctree)
-
- @property
- def _nitpick_ignore(self):
- # type: () -> List[str]
- warnings.warn('env._nitpick_ignore is deprecated. '
- 'Please use config.nitpick_ignore instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.config.nitpick_ignore
-
- @staticmethod
- def load(f, app=None):
- # type: (IO, Sphinx) -> BuildEnvironment
- warnings.warn('BuildEnvironment.load() is deprecated. '
- 'Please use pickle.load() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- try:
- env = pickle.load(f)
- except Exception as exc:
- # This can happen for example when the pickle is from a
- # different version of Sphinx.
- raise OSError(exc)
- if app:
- env.app = app
- env.config.values = app.config.values
- return env
-
- @classmethod
- def loads(cls, string, app=None):
- # type: (bytes, Sphinx) -> BuildEnvironment
- warnings.warn('BuildEnvironment.loads() is deprecated. '
- 'Please use pickle.loads() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- io = BytesIO(string)
- return cls.load(io, app)
-
- @classmethod
- def frompickle(cls, filename, app):
- # type: (str, Sphinx) -> BuildEnvironment
- warnings.warn('BuildEnvironment.frompickle() is deprecated. '
- 'Please use pickle.load() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- with open(filename, 'rb') as f:
- return cls.load(f, app)
-
- @staticmethod
- def dump(env, f):
- # type: (BuildEnvironment, IO) -> None
- warnings.warn('BuildEnvironment.dump() is deprecated. '
- 'Please use pickle.dump() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- pickle.dump(env, f, pickle.HIGHEST_PROTOCOL)
-
- @classmethod
- def dumps(cls, env):
- # type: (BuildEnvironment) -> bytes
- warnings.warn('BuildEnvironment.dumps() is deprecated. '
- 'Please use pickle.dumps() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- io = BytesIO()
- cls.dump(env, io)
- return io.getvalue()
-
- def topickle(self, filename):
- # type: (str) -> None
- warnings.warn('env.topickle() is deprecated. '
- 'Please use pickle.dump() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- with open(filename, 'wb') as f:
- self.dump(self, f)
-
- @property
- def versionchanges(self):
- # type: () -> Dict[str, List[Tuple[str, str, int, str, str, str]]]
- warnings.warn('env.versionchanges() is deprecated. '
- 'Please use ChangeSetDomain instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.domaindata['changeset']['changes']
-
- def note_versionchange(self, type, version, node, lineno):
- # type: (str, str, addnodes.versionmodified, int) -> None
- warnings.warn('env.note_versionchange() is deprecated. '
- 'Please use ChangeSetDomain.note_changeset() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- node['type'] = type
- node['version'] = version
- node.line = lineno
- self.get_domain('changeset').note_changeset(node) # type: ignore
-
-
-from sphinx.errors import NoUri # NOQA
-
-
-deprecated_alias('sphinx.environment',
- {
- 'NoUri': NoUri,
- },
- RemovedInSphinx30Warning)
diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py
index 5d96affa4..8446ab66b 100644
--- a/sphinx/ext/autodoc/__init__.py
+++ b/sphinx/ext/autodoc/__init__.py
@@ -18,9 +18,7 @@ from typing import Any
from docutils.statemachine import StringList
import sphinx
-from sphinx.deprecation import (
- RemovedInSphinx30Warning, RemovedInSphinx40Warning, deprecated_alias
-)
+from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.ext.autodoc.importer import import_object, get_object_members
from sphinx.ext.autodoc.mock import mock
from sphinx.locale import _, __
@@ -1448,39 +1446,6 @@ def autodoc_attrgetter(app, obj, name, *defargs):
return safe_getattr(obj, name, *defargs)
-def merge_autodoc_default_flags(app, config):
- # type: (Sphinx, Config) -> None
- """This merges the autodoc_default_flags to autodoc_default_options."""
- if not config.autodoc_default_flags:
- return
-
- # Note: this option will be removed in Sphinx-4.0. But I marked this as
- # RemovedInSphinx *30* Warning because we have to emit warnings for users
- # who will be still in use with Sphinx-3.x. So we should replace this by
- # logger.warning() on 3.0.0 release.
- warnings.warn('autodoc_default_flags is now deprecated. '
- 'Please use autodoc_default_options instead.',
- RemovedInSphinx30Warning, stacklevel=2)
-
- for option in config.autodoc_default_flags:
- if isinstance(option, str):
- config.autodoc_default_options[option] = None
- else:
- logger.warning(
- __("Ignoring invalid option in autodoc_default_flags: %r"),
- option, type='autodoc'
- )
-
-
-from sphinx.ext.autodoc.mock import _MockImporter # NOQA
-
-deprecated_alias('sphinx.ext.autodoc',
- {
- '_MockImporter': _MockImporter,
- },
- RemovedInSphinx40Warning)
-
-
def setup(app):
# type: (Sphinx) -> Dict[str, Any]
app.add_autodocumenter(ModuleDocumenter)
@@ -1505,6 +1470,4 @@ def setup(app):
app.add_event('autodoc-process-signature')
app.add_event('autodoc-skip-member')
- app.connect('config-inited', merge_autodoc_default_flags)
-
return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
diff --git a/sphinx/ext/autodoc/importer.py b/sphinx/ext/autodoc/importer.py
index a06d93d52..557461fd4 100644
--- a/sphinx/ext/autodoc/importer.py
+++ b/sphinx/ext/autodoc/importer.py
@@ -150,12 +150,11 @@ def get_object_members(subject, objpath, attrgetter, analyzer=None):
from sphinx.ext.autodoc.mock import ( # NOQA
- _MockImporter, _MockModule, _MockObject, MockFinder, MockLoader, mock
+ _MockModule, _MockObject, MockFinder, MockLoader, mock
)
deprecated_alias('sphinx.ext.autodoc.importer',
{
- '_MockImporter': _MockImporter,
'_MockModule': _MockModule,
'_MockObject': _MockObject,
'MockFinder': MockFinder,
diff --git a/sphinx/ext/autodoc/mock.py b/sphinx/ext/autodoc/mock.py
index 6ae389258..d896bdde2 100644
--- a/sphinx/ext/autodoc/mock.py
+++ b/sphinx/ext/autodoc/mock.py
@@ -11,12 +11,10 @@
import contextlib
import os
import sys
-import warnings
from importlib.abc import Loader, MetaPathFinder
from importlib.machinery import ModuleSpec
from types import FunctionType, MethodType, ModuleType
-from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.util import logging
if False:
@@ -94,16 +92,12 @@ class _MockModule(ModuleType):
"""Used by autodoc_mock_imports."""
__file__ = os.devnull
- def __init__(self, name, loader=None):
- # type: (str, _MockImporter) -> None
+ def __init__(self, name):
+ # type: (str) -> None
super().__init__(name)
self.__all__ = [] # type: List[str]
self.__path__ = [] # type: List[str]
- if loader is not None:
- warnings.warn('The loader argument for _MockModule is deprecated.',
- RemovedInSphinx30Warning)
-
def __getattr__(self, name):
# type: (str) -> _MockObject
return _make_subclass(name, self.__name__)()
@@ -113,48 +107,6 @@ class _MockModule(ModuleType):
return self.__name__
-class _MockImporter(MetaPathFinder):
- def __init__(self, names):
- # type: (List[str]) -> None
- self.names = names
- self.mocked_modules = [] # type: List[str]
- # enable hook by adding itself to meta_path
- sys.meta_path.insert(0, self)
-
- warnings.warn('_MockImporter is now deprecated.',
- RemovedInSphinx30Warning)
-
- def disable(self):
- # type: () -> None
- # remove `self` from `sys.meta_path` to disable import hook
- sys.meta_path = [i for i in sys.meta_path if i is not self]
- # remove mocked modules from sys.modules to avoid side effects after
- # running auto-documenter
- for m in self.mocked_modules:
- if m in sys.modules:
- del sys.modules[m]
-
- def find_module(self, name, path=None):
- # type: (str, Sequence[Union[bytes, str]]) -> Any
- # check if name is (or is a descendant of) one of our base_packages
- for n in self.names:
- if n == name or name.startswith(n + '.'):
- return self
- return None
-
- def load_module(self, name):
- # type: (str) -> ModuleType
- if name in sys.modules:
- # module has already been imported, return it
- return sys.modules[name]
- else:
- logger.debug('[autodoc] adding a mock module %s!', name)
- module = _MockModule(name, self)
- sys.modules[name] = module
- self.mocked_modules.append(name)
- return module
-
-
class MockLoader(Loader):
"""A loader for mocking."""
def __init__(self, finder):
diff --git a/sphinx/ext/mathbase.py b/sphinx/ext/mathbase.py
deleted file mode 100644
index 0c89fd1ed..000000000
--- a/sphinx/ext/mathbase.py
+++ /dev/null
@@ -1,84 +0,0 @@
-"""
- sphinx.ext.mathbase
- ~~~~~~~~~~~~~~~~~~~
-
- Set up math support in source files and LaTeX/text output.
-
- :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import warnings
-
-from docutils import nodes
-from docutils.parsers.rst.roles import math_role as math_role_base
-
-from sphinx.addnodes import math, math_block as displaymath # NOQA # to keep compatibility
-from sphinx.builders.latex.nodes import math_reference as eqref # NOQA # to keep compatibility
-from sphinx.deprecation import RemovedInSphinx30Warning
-from sphinx.directives.patches import MathDirective as MathDirectiveBase
-from sphinx.domains.math import MathDomain # NOQA # to keep compatibility
-from sphinx.domains.math import MathReferenceRole as EqXRefRole # NOQA # to keep compatibility
-
-if False:
- # For type annotation
- from typing import Callable, Tuple # NOQA
- from sphinx.application import Sphinx # NOQA
- from sphinx.writers.html import HTMLTranslator # NOQA
-
-
-class MathDirective(MathDirectiveBase):
- def run(self):
- warnings.warn('sphinx.ext.mathbase.MathDirective is moved to '
- 'sphinx.directives.patches package.',
- RemovedInSphinx30Warning, stacklevel=2)
- return super().run()
-
-
-def math_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
- warnings.warn('sphinx.ext.mathbase.math_role() is deprecated. '
- 'Please use docutils.parsers.rst.roles.math_role() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return math_role_base(role, rawtext, text, lineno, inliner, options, content)
-
-
-def get_node_equation_number(writer, node):
- # type: (HTMLTranslator, nodes.math_block) -> str
- warnings.warn('sphinx.ext.mathbase.get_node_equation_number() is moved to '
- 'sphinx.util.math package.',
- RemovedInSphinx30Warning, stacklevel=2)
- from sphinx.util.math import get_node_equation_number
- return get_node_equation_number(writer, node)
-
-
-def wrap_displaymath(text, label, numbering):
- # type: (str, str, bool) -> str
- warnings.warn('sphinx.ext.mathbase.wrap_displaymath() is moved to '
- 'sphinx.util.math package.',
- RemovedInSphinx30Warning, stacklevel=2)
- from sphinx.util.math import wrap_displaymath
- return wrap_displaymath(text, label, numbering)
-
-
-def is_in_section_title(node):
- # type: (nodes.Element) -> bool
- """Determine whether the node is in a section title"""
- from sphinx.util.nodes import traverse_parent
-
- warnings.warn('is_in_section_title() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
-
- for ancestor in traverse_parent(node):
- if isinstance(ancestor, nodes.title) and \
- isinstance(ancestor.parent, nodes.section):
- return True
- return False
-
-
-def setup_math(app, htmlinlinevisitors, htmldisplayvisitors):
- # type: (Sphinx, Tuple[Callable, Callable], Tuple[Callable, Callable]) -> None
- warnings.warn('setup_math() is deprecated. '
- 'Please use app.add_html_math_renderer() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
-
- app.add_html_math_renderer('unknown', htmlinlinevisitors, htmldisplayvisitors)
diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py
index 2997dc216..5de8f7f5e 100644
--- a/sphinx/ext/viewcode.py
+++ b/sphinx/ext/viewcode.py
@@ -9,13 +9,11 @@
"""
import traceback
-import warnings
from docutils import nodes
import sphinx
from sphinx import addnodes
-from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.locale import _, __
from sphinx.pycode import ModuleAnalyzer
from sphinx.util import get_full_modname, logging, status_iterator
@@ -238,14 +236,6 @@ def collect_pages(app):
yield ('_modules/index', context, 'page.html')
-def migrate_viewcode_import(app, config):
- # type: (Sphinx, Config) -> None
- if config.viewcode_import is not None:
- warnings.warn('viewcode_import was renamed to viewcode_follow_imported_members. '
- 'Please update your configuration.',
- RemovedInSphinx30Warning, stacklevel=2)
-
-
def setup(app):
# type: (Sphinx) -> Dict[str, Any]
app.add_config_value('viewcode_import', None, False)
diff --git a/sphinx/highlighting.py b/sphinx/highlighting.py
index c53149ce6..c194738f8 100644
--- a/sphinx/highlighting.py
+++ b/sphinx/highlighting.py
@@ -8,9 +8,6 @@
:license: BSD, see LICENSE for details.
"""
-import html
-import warnings
-
from pygments import highlight
from pygments.filters import ErrorToken
from pygments.formatters import HtmlFormatter, LatexFormatter
@@ -21,8 +18,6 @@ from pygments.lexers import PythonLexer, Python3Lexer, PythonConsoleLexer, \
from pygments.styles import get_style_by_name
from pygments.util import ClassNotFound
-from sphinx.deprecation import RemovedInSphinx30Warning
-from sphinx.ext import doctest
from sphinx.locale import __
from sphinx.pygments_styles import SphinxStyle, NoneStyle
from sphinx.util import logging
@@ -66,8 +61,8 @@ class PygmentsBridge:
html_formatter = HtmlFormatter
latex_formatter = LatexFormatter
- def __init__(self, dest='html', stylename='sphinx', trim_doctest_flags=None):
- # type: (str, str, bool) -> None
+ def __init__(self, dest='html', stylename='sphinx'):
+ # type: (str, str) -> None
self.dest = dest
if stylename is None or stylename == 'sphinx':
style = SphinxStyle
@@ -86,30 +81,11 @@ class PygmentsBridge:
self.formatter = self.latex_formatter
self.formatter_args['commandprefix'] = 'PYG'
- self.trim_doctest_flags = trim_doctest_flags
- if trim_doctest_flags is not None:
- warnings.warn('trim_doctest_flags option for PygmentsBridge is now deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
-
def get_formatter(self, **kwargs):
# type: (Any) -> Formatter
kwargs.update(self.formatter_args)
return self.formatter(**kwargs)
- def unhighlighted(self, source):
- # type: (str) -> str
- warnings.warn('PygmentsBridge.unhighlighted() is now deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- if self.dest == 'html':
- return '<pre>' + html.escape(source) + '</pre>\n'
- else:
- # first, escape highlighting characters like Pygments does
- source = source.translate(escape_hl_chars)
- # then, escape all characters nonrepresentable in LaTeX
- source = source.translate(tex_hl_escape_map_new)
- return '\\begin{Verbatim}[commandchars=\\\\\\{\\}]\n' + \
- source + '\\end{Verbatim}\n'
-
def highlight_block(self, source, lang, opts=None, location=None, force=False, **kwargs):
# type: (str, str, Any, Any, bool, Any) -> str
if not isinstance(source, str):
@@ -145,11 +121,6 @@ class PygmentsBridge:
else:
lexer.add_filter('raiseonerror')
- # trim doctest options if wanted
- if isinstance(lexer, PythonConsoleLexer) and self.trim_doctest_flags:
- source = doctest.blankline_re.sub('', source)
- source = doctest.doctestopt_re.sub('', source)
-
# highlight via Pygments
formatter = self.get_formatter(**kwargs)
try:
diff --git a/sphinx/io.py b/sphinx/io.py
index b5b57d065..105ed4397 100644
--- a/sphinx/io.py
+++ b/sphinx/io.py
@@ -8,17 +8,14 @@
:license: BSD, see LICENSE for details.
"""
import codecs
-import warnings
from typing import Any
from docutils.core import Publisher
from docutils.io import FileInput, NullOutput
from docutils.parsers.rst import Parser as RSTParser
from docutils.readers import standalone
-from docutils.statemachine import StringList, string2lines
from docutils.writers import UnfilteredWriter
-from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.transforms import (
AutoIndexUpgrader, DoctreeReadEvent, FigureAligner, SphinxTransformer
)
@@ -29,7 +26,6 @@ from sphinx.transforms.references import SphinxDomains
from sphinx.util import logging
from sphinx.util import UnicodeDecodeErrorHandler
from sphinx.util.docutils import LoggingReporter
-from sphinx.util.rst import append_epilog, docinfo_re, prepend_prolog
from sphinx.versioning import UIDTransform
if False:
@@ -136,19 +132,6 @@ class SphinxI18nReader(SphinxBaseReader):
super().__init__(app, *args, **kwargs)
- def set_lineno_for_reporter(self, lineno):
- # type: (int) -> None
- """Stores the source line number of original text."""
- warnings.warn('SphinxI18nReader.set_lineno_for_reporter() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
-
- @property
- def line(self):
- # type: () -> int
- warnings.warn('SphinxI18nReader.line is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return 0
-
class SphinxDummyWriter(UnfilteredWriter):
"""Dummy writer module used for generating doctree."""
@@ -166,99 +149,14 @@ def SphinxDummySourceClass(source, *args, **kwargs):
return source
-class SphinxBaseFileInput(FileInput):
- """A base class of SphinxFileInput.
-
- It supports to replace unknown Unicode characters to '?'.
- """
-
- def __init__(self, app, env, *args, **kwds):
- # type: (Sphinx, BuildEnvironment, Any, Any) -> None
- self.app = app
- self.env = env
-
- warnings.warn('%s is deprecated.' % self.__class__.__name__,
- RemovedInSphinx30Warning, stacklevel=2)
-
- kwds['error_handler'] = 'sphinx' # py3: handle error on open.
- super().__init__(*args, **kwds)
-
- def warn_and_replace(self, error):
- # type: (Any) -> Tuple
- return UnicodeDecodeErrorHandler(self.env.docname)(error)
-
-
class SphinxFileInput(FileInput):
"""A basic FileInput for Sphinx."""
- supported = ('*',) # RemovedInSphinx30Warning
-
def __init__(self, *args, **kwargs):
# type: (Any, Any) -> None
kwargs['error_handler'] = 'sphinx'
super().__init__(*args, **kwargs)
-class SphinxRSTFileInput(SphinxBaseFileInput):
- """A reST FileInput for Sphinx.
-
- This FileInput automatically prepends and appends text by :confval:`rst_prolog` and
- :confval:`rst_epilog`.
-
- .. important::
-
- This FileInput uses an instance of ``StringList`` as a return value of ``read()``
- method to indicate original source filename and line numbers after prepending and
- appending.
- For that reason, ``sphinx.parsers.RSTParser`` should be used with this to parse
- a content correctly.
- """
- supported = ('restructuredtext',)
-
- def prepend_prolog(self, text, prolog):
- # type: (StringList, str) -> None
- docinfo = self.count_docinfo_lines(text)
- if docinfo:
- # insert a blank line after docinfo
- text.insert(docinfo, '', '<generated>', 0)
- docinfo += 1
-
- # insert prolog (after docinfo if exists)
- for lineno, line in enumerate(prolog.splitlines()):
- text.insert(docinfo + lineno, line, '<rst_prolog>', lineno)
-
- text.insert(docinfo + lineno + 1, '', '<generated>', 0)
-
- def append_epilog(self, text, epilog):
- # type: (StringList, str) -> None
- # append a blank line and rst_epilog
- text.append('', '<generated>', 0)
- for lineno, line in enumerate(epilog.splitlines()):
- text.append(line, '<rst_epilog>', lineno)
-
- def read(self): # type: ignore
- # type: () -> StringList
- inputstring = super().read()
- lines = string2lines(inputstring, convert_whitespace=True)
- content = StringList()
- for lineno, line in enumerate(lines):
- content.append(line, self.source_path, lineno)
-
- prepend_prolog(content, self.env.config.rst_prolog)
- append_epilog(content, self.env.config.rst_epilog)
-
- return content
-
- def count_docinfo_lines(self, content):
- # type: (StringList) -> int
- if len(content) == 0:
- return 0
- else:
- for lineno, line in enumerate(content.data):
- if not docinfo_re.match(line):
- break
- return lineno
-
-
class FiletypeNotFoundError(Exception):
pass
diff --git a/sphinx/locale/__init__.py b/sphinx/locale/__init__.py
index 6ae20d0d0..d18d075d4 100644
--- a/sphinx/locale/__init__.py
+++ b/sphinx/locale/__init__.py
@@ -10,12 +10,9 @@
import gettext
import locale
-import warnings
from collections import UserString, defaultdict
from gettext import NullTranslations
-from sphinx.deprecation import RemovedInSphinx30Warning
-
if False:
# For type annotation
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union # NOQA
@@ -127,26 +124,6 @@ class _TranslationProxy(UserString):
return '<%s broken>' % self.__class__.__name__
-def mygettext(string):
- # type: (str) -> str
- """Used instead of _ when creating TranslationProxies, because _ is
- not bound yet at that time.
- """
- warnings.warn('sphinx.locale.mygettext() is deprecated. Please use `_()` instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return _(string)
-
-
-def lazy_gettext(string):
- # type: (str) -> str
- """A lazy version of `gettext`."""
- # if isinstance(string, _TranslationProxy):
- # return string
- warnings.warn('sphinx.locale.laxy_gettext() is deprecated. Please use `_()` instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return _TranslationProxy(mygettext, string) # type: ignore
-
-
translators = defaultdict(NullTranslations) # type: Dict[Tuple[str, str], NullTranslations]
@@ -295,12 +272,6 @@ _ = get_translation('sphinx')
__ = get_translation('sphinx', 'console')
-def l_(*args):
- warnings.warn('sphinx.locale.l_() is deprecated. Please use `_()` instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return _(*args)
-
-
# labels
admonitionlabels = {
'attention': _('Attention'),
diff --git a/sphinx/make_mode.py b/sphinx/make_mode.py
deleted file mode 100644
index c1da2a5fa..000000000
--- a/sphinx/make_mode.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""
- sphinx.make_mode
- ~~~~~~~~~~~~~~~~
-
- sphinx-build -M command-line handling.
-
- This replaces the old, platform-dependent and once-generated content
- of Makefile / make.bat.
-
- This is in its own module so that importing it is fast. It should not
- import the main Sphinx modules (like sphinx.applications, sphinx.builders).
-
- :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import warnings
-
-from sphinx.cmd import make_mode
-from sphinx.deprecation import RemovedInSphinx30Warning
-
-
-BUILDERS = make_mode.BUILDERS
-
-
-class Make(make_mode.Make):
- def __init__(self, *args):
- warnings.warn('sphinx.make_mode.Make is deprecated. '
- 'Please use sphinx.cmd.make_mode.Make instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- super().__init__(*args)
-
-
-def run_make_mode(args):
- warnings.warn('sphinx.make_mode.run_make_mode() is deprecated. '
- 'Please use sphinx.cmd.make_mode.run_make_mode() instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- return make_mode.run_make_mode(args)
diff --git a/sphinx/registry.py b/sphinx/registry.py
index 311270ccb..32dbd2f55 100644
--- a/sphinx/registry.py
+++ b/sphinx/registry.py
@@ -9,14 +9,11 @@
"""
import traceback
-import warnings
-from inspect import isclass
from types import MethodType
from docutils.parsers.rst import Directive
from pkg_resources import iter_entry_points
-from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.domains import ObjType
from sphinx.domains.std import GenericObject, Target
from sphinx.errors import ExtensionError, SphinxError, VersionRequirementError
@@ -25,7 +22,6 @@ from sphinx.locale import __
from sphinx.parsers import Parser as SphinxParser
from sphinx.roles import XRefRole
from sphinx.util import logging
-from sphinx.util.docutils import directive_helper
from sphinx.util.logging import prefixed_warnings
if False:
@@ -181,18 +177,9 @@ class SphinxComponentRegistry:
yield domain
- def override_domain(self, domain):
- # type: (Type[Domain]) -> None
- warnings.warn('registry.override_domain() is deprecated. '
- 'Use app.add_domain(domain, override=True) instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- self.add_domain(domain, override=True)
-
- def add_directive_to_domain(self, domain, name, obj, has_content=None, argument_spec=None,
- override=False, **option_spec):
- # type: (str, str, Any, bool, Any, bool, Any) -> None
- logger.debug('[app] adding directive to domain: %r',
- (domain, name, obj, has_content, argument_spec, option_spec))
+ def add_directive_to_domain(self, domain, name, cls, override=False):
+ # type: (str, str, Type[Directive], bool) -> None
+ logger.debug('[app] adding directive to domain: %r', (domain, name, cls))
if domain not in self.domains:
raise ExtensionError(__('domain %s not yet registered') % domain)
@@ -200,10 +187,7 @@ class SphinxComponentRegistry:
if name in directives and not override:
raise ExtensionError(__('The %r directive is already registered to domain %s') %
(name, domain))
- if not isclass(obj) or not issubclass(obj, Directive):
- directives[name] = directive_helper(obj, has_content, argument_spec, **option_spec)
- else:
- directives[name] = obj
+ directives[name] = cls
def add_role_to_domain(self, domain, name, role, override=False):
# type: (str, str, Union[RoleFunction, XRefRole], bool) -> None
@@ -279,29 +263,9 @@ class SphinxComponentRegistry:
else:
self.source_suffix[suffix] = filetype
- def add_source_parser(self, *args, **kwargs):
- # type: (Any, bool) -> None
- logger.debug('[app] adding search source_parser: %r', args)
- if len(args) == 1:
- # new sytle arguments: (source_parser)
- suffix = None # type: str
- 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, stacklevel=3)
- suffix = args[0]
- parser = args[1]
-
- if suffix:
- self.add_source_suffix(suffix, suffix, override=True)
-
- if len(parser.supported) == 0:
- warnings.warn('Old source_parser has been detected. Please fill Parser.supported '
- 'attribute: %s' % parser.__name__,
- RemovedInSphinx30Warning, stacklevel=3)
-
+ def add_source_parser(self, parser, **kwargs):
+ # type: (Type[Parser], bool) -> None
+ logger.debug('[app] adding search source_parser: %r', parser)
# create a map from filetype to parser
for filetype in parser.supported:
if filetype in self.source_parsers and not kwargs.get('override'):
@@ -310,12 +274,6 @@ class SphinxComponentRegistry:
else:
self.source_parsers[filetype] = parser
- # also maps suffix to 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: (str) -> Type[Parser]
try:
@@ -335,16 +293,6 @@ class SphinxComponentRegistry:
parser.set_application(app)
return parser
- def add_source_input(self, input_class, override=False):
- # type: (Type[SphinxFileInput], bool) -> None
- warnings.warn('registry.source_input() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- for filetype in input_class.supported:
- if filetype in self.source_inputs and not override:
- raise ExtensionError(__('source_input for %r is already registered') %
- filetype)
- self.source_inputs[filetype] = input_class
-
def get_source_input(self, filetype):
# type: (str) -> Type[Input]
try:
diff --git a/sphinx/search/ja.py b/sphinx/search/ja.py
index 0c11af74d..e1f18209a 100644
--- a/sphinx/search/ja.py
+++ b/sphinx/search/ja.py
@@ -19,7 +19,6 @@
import os
import re
import sys
-import warnings
try:
import MeCab
@@ -33,7 +32,6 @@ try:
except ImportError:
janome_module = False
-from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.errors import SphinxError, ExtensionError
from sphinx.search import SearchLanguage
from sphinx.util import import_object
@@ -543,22 +541,10 @@ class SearchJapanese(SearchLanguage):
"""
lang = 'ja'
language_name = 'Japanese'
- splitters = {
- 'default': 'sphinx.search.ja.DefaultSplitter',
- 'mecab': 'sphinx.search.ja.MecabSplitter',
- 'janome': 'sphinx.search.ja.JanomeSplitter',
- }
def init(self, options):
# type: (Dict) -> None
- type = options.get('type', 'sphinx.search.ja.DefaultSplitter')
- if type in self.splitters:
- dotted_path = self.splitters[type]
- warnings.warn('html_search_options["type"]: %s is deprecated. '
- 'Please give "%s" instead.' % (type, dotted_path),
- RemovedInSphinx30Warning, stacklevel=2)
- else:
- dotted_path = type
+ dotted_path = options.get('type', 'sphinx.search.ja.DefaultSplitter')
try:
self.splitter = import_object(dotted_path)(options)
except ExtensionError:
diff --git a/sphinx/transforms/post_transforms/compat.py b/sphinx/transforms/post_transforms/compat.py
deleted file mode 100644
index 67b67f8d4..000000000
--- a/sphinx/transforms/post_transforms/compat.py
+++ /dev/null
@@ -1,90 +0,0 @@
-"""
- sphinx.transforms.post_transforms.compat
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Post transforms for compatibility
-
- :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import warnings
-
-from docutils import nodes
-from docutils.writers.docutils_xml import XMLTranslator
-
-from sphinx.addnodes import math_block, displaymath
-from sphinx.deprecation import RemovedInSphinx30Warning
-from sphinx.transforms import SphinxTransform
-from sphinx.util import logging
-
-if False:
- # For type annotation
- from typing import Any, Dict # NOQA
- from sphinx.application import Sphinx # NOQA
-
-logger = logging.getLogger(__name__)
-
-
-class MathNodeMigrator(SphinxTransform):
- """Migrate a math node to docutils'.
-
- For a long time, Sphinx uses an original node for math. Since 1.8,
- Sphinx starts to use a math node of docutils'. This transform converts
- old and new nodes to keep compatibility.
- """
- default_priority = 999
-
- def apply(self, **kwargs):
- # type: (Any) -> None
- for math_node in self.document.traverse(nodes.math):
- # case: old styled ``math`` node generated by old extensions
- if len(math_node) == 0:
- warnings.warn("math node for Sphinx was replaced by docutils'. "
- "Please use ``docutils.nodes.math`` instead.",
- RemovedInSphinx30Warning)
- equation = math_node['latex']
- math_node += nodes.Text(equation, equation)
-
- translator = self.app.builder.get_translator_class()
- if hasattr(translator, 'visit_displaymath') and translator != XMLTranslator:
- # case: old translators which does not support ``math_block`` node
- warnings.warn("Translator for %s does not support math_block node'. "
- "Please update your extension." % translator,
- RemovedInSphinx30Warning)
- for old_math_block_node in self.document.traverse(math_block):
- alt = displaymath(latex=old_math_block_node.astext(),
- number=old_math_block_node.get('number'),
- label=old_math_block_node.get('label'),
- nowrap=old_math_block_node.get('nowrap'),
- docname=old_math_block_node.get('docname'))
- old_math_block_node.replace_self(alt)
- elif getattr(self.app.builder, 'math_renderer_name', None) == 'unknown':
- # case: math extension provides old styled math renderer
- for math_block_node in self.document.traverse(nodes.math_block):
- math_block_node['latex'] = math_block_node.astext()
-
- # case: old styled ``displaymath`` node generated by old extensions
- for math_block_node in self.document.traverse(math_block):
- if len(math_block_node) == 0:
- warnings.warn("math node for Sphinx was replaced by docutils'. "
- "Please use ``docutils.nodes.math_block`` instead.",
- RemovedInSphinx30Warning)
- if isinstance(math_block_node, displaymath):
- newnode = nodes.math_block('', math_block_node['latex'],
- **math_block_node.attributes)
- math_block_node.replace_self(newnode)
- else:
- latex = math_block_node['latex']
- math_block_node += nodes.Text(latex, latex)
-
-
-def setup(app):
- # type: (Sphinx) -> Dict[str, Any]
- app.add_post_transform(MathNodeMigrator)
-
- return {
- 'version': 'builtin',
- 'parallel_read_safe': True,
- 'parallel_write_safe': True,
- }
diff --git a/sphinx/util/__init__.py b/sphinx/util/__init__.py
index 2ebae8768..cc2cd9aa1 100644
--- a/sphinx/util/__init__.py
+++ b/sphinx/util/__init__.py
@@ -26,21 +26,18 @@ from os import path
from time import mktime, strptime
from urllib.parse import urlsplit, urlunsplit, quote_plus, parse_qsl, urlencode
-from docutils.utils import relative_path
-
-from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
+from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.errors import PycodeError, SphinxParallelError, ExtensionError
from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.console import strip_colors, colorize, bold, term_width_line # type: ignore
-from sphinx.util.fileutil import copy_asset_file
from sphinx.util import smartypants # noqa
# import other utilities; partly for backwards compatibility, so don't
# prune unused ones indiscriminately
from sphinx.util.osutil import ( # noqa
SEP, os_path, relative_uri, ensuredir, walk, mtimes_of_files, movefile,
- copyfile, copytimes, make_filename, ustrftime)
+ copyfile, copytimes, make_filename)
from sphinx.util.nodes import ( # noqa
nested_parse_with_titles, split_explicit_title, explicit_title_re,
caption_ref_re)
@@ -196,36 +193,6 @@ class DownloadFiles(dict):
self.add_file(docname, filename)
-def copy_static_entry(source, targetdir, builder, context={},
- exclude_matchers=(), level=0):
- # type: (str, str, Any, Dict, Tuple[Callable, ...], int) -> None
- """[DEPRECATED] Copy a HTML builder static_path entry from source to targetdir.
-
- Handles all possible cases of files, directories and subdirectories.
- """
- warnings.warn('sphinx.util.copy_static_entry is deprecated for removal',
- RemovedInSphinx30Warning, stacklevel=2)
-
- if exclude_matchers:
- relpath = relative_path(path.join(builder.srcdir, 'dummy'), source)
- for matcher in exclude_matchers:
- if matcher(relpath):
- return
- if path.isfile(source):
- copy_asset_file(source, targetdir, context, builder.templates)
- elif path.isdir(source):
- ensuredir(targetdir)
- for entry in os.listdir(source):
- if entry.startswith('.'):
- continue
- newtarget = targetdir
- if path.isdir(path.join(source, entry)):
- newtarget = path.join(targetdir, entry)
- copy_static_entry(path.join(source, entry), newtarget,
- builder, context, level=level + 1,
- exclude_matchers=exclude_matchers)
-
-
_DEBUG_HEADER = '''\
# Sphinx version: %s
# Python version: %s (%s)
diff --git a/sphinx/util/compat.py b/sphinx/util/compat.py
index 5d8cbb3db..805c17e5d 100644
--- a/sphinx/util/compat.py
+++ b/sphinx/util/compat.py
@@ -14,9 +14,8 @@ import warnings
from docutils.utils import get_source_line
from sphinx import addnodes
-from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
+from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.transforms import SphinxTransform
-from sphinx.util import import_object
if False:
# For type annotation
@@ -25,18 +24,6 @@ if False:
from sphinx.config import Config # NOQA
-def deprecate_source_parsers(app, config):
- # type: (Sphinx, Config) -> None
- if config.source_parsers:
- warnings.warn('The config variable "source_parsers" is deprecated. '
- 'Please use app.add_source_parser() API instead.',
- RemovedInSphinx30Warning)
- for suffix, parser in config.source_parsers.items():
- if isinstance(parser, str):
- parser = import_object(parser, 'source parser')
- app.add_source_parser(suffix, parser)
-
-
def register_application_for_autosummary(app):
# type: (Sphinx) -> None
"""Register application object to autosummary module.
@@ -69,7 +56,6 @@ class IndexEntriesMigrator(SphinxTransform):
def setup(app):
# type: (Sphinx) -> Dict[str, Any]
app.add_transform(IndexEntriesMigrator)
- app.connect('config-inited', deprecate_source_parsers)
app.connect('builder-inited', register_application_for_autosummary)
return {
diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py
index eebfec464..d38c780f4 100644
--- a/sphinx/util/docutils.py
+++ b/sphinx/util/docutils.py
@@ -10,8 +10,6 @@
import os
import re
-import types
-import warnings
from contextlib import contextmanager
from copy import copy
from distutils.version import LooseVersion
@@ -21,13 +19,11 @@ from typing import IO, cast
import docutils
from docutils import nodes
from docutils.io import FileOutput
-from docutils.parsers.rst import Directive, directives, roles, convert_directive_function
+from docutils.parsers.rst import Directive, directives, roles
from docutils.statemachine import StateMachine
from docutils.utils import Reporter, unescape
-from sphinx.deprecation import RemovedInSphinx30Warning
-from sphinx.errors import ExtensionError, SphinxError
-from sphinx.locale import __
+from sphinx.errors import SphinxError
from sphinx.util import logging
logger = logging.getLogger(__name__)
@@ -304,24 +300,6 @@ def is_html5_writer_available():
return __version_info__ > (0, 13, 0)
-def directive_helper(obj, has_content=None, argument_spec=None, **option_spec):
- # type: (Any, bool, Tuple[int, int, bool], Any) -> Any
- warnings.warn('function based directive support is now deprecated. '
- 'Use class based directive instead.',
- RemovedInSphinx30Warning)
-
- if isinstance(obj, (types.FunctionType, types.MethodType)):
- obj.content = has_content # type: ignore
- obj.arguments = argument_spec or (0, 0, False) # type: ignore
- obj.options = option_spec # type: ignore
- return convert_directive_function(obj)
- else:
- if has_content or argument_spec or option_spec:
- raise ExtensionError(__('when adding directive classes, no '
- 'additional arguments may be given'))
- return obj
-
-
@contextmanager
def switch_source_input(state, content):
# type: (State, StringList) -> Generator[None, None, None]
diff --git a/sphinx/util/i18n.py b/sphinx/util/i18n.py
index e342b1246..89534f5ae 100644
--- a/sphinx/util/i18n.py
+++ b/sphinx/util/i18n.py
@@ -19,7 +19,7 @@ import babel.dates
from babel.messages.mofile import write_mo
from babel.messages.pofile import read_po
-from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
+from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.errors import SphinxError
from sphinx.locale import __
from sphinx.util import logging
@@ -161,10 +161,9 @@ def find_catalog_files(docname, srcdir, locale_dirs, lang, compaction):
return files
-def find_catalog_source_files(locale_dirs, locale, domains=None, gettext_compact=None,
- charset='utf-8', force_all=False,
- excluded=Matcher([])):
- # type: (List[str], str, List[str], bool, str, bool, Matcher) -> Set[CatalogInfo]
+def find_catalog_source_files(locale_dirs, locale, domains=None, charset='utf-8',
+ force_all=False, excluded=Matcher([])):
+ # type: (List[str], str, List[str], str, bool, Matcher) -> Set[CatalogInfo]
"""
:param list locale_dirs:
list of path as `['locale_dir1', 'locale_dir2', ...]` to find
@@ -180,9 +179,6 @@ def find_catalog_source_files(locale_dirs, locale, domains=None, gettext_compact
"""
warnings.warn('find_catalog_source_files() is deprecated.',
RemovedInSphinx40Warning, stacklevel=2)
- if gettext_compact is not None:
- warnings.warn('gettext_compact argument for find_catalog_source_files() '
- 'is deprecated.', RemovedInSphinx30Warning, stacklevel=2)
catalogs = set() # type: Set[CatalogInfo]
diff --git a/sphinx/util/images.py b/sphinx/util/images.py
index 0e5f3e81b..76bffd88c 100644
--- a/sphinx/util/images.py
+++ b/sphinx/util/images.py
@@ -10,16 +10,12 @@
import base64
import imghdr
-import warnings
from collections import OrderedDict
-from io import BytesIO
from os import path
from typing import NamedTuple
import imagesize
-from sphinx.deprecation import RemovedInSphinx30Warning
-
try:
from PIL import Image
except ImportError:
@@ -72,17 +68,11 @@ def guess_mimetype_for_stream(stream, default=None):
return default
-def guess_mimetype(filename='', content=None, default=None):
- # type: (str, bytes, str) -> str
+def guess_mimetype(filename, default=None):
+ # type: (str, str) -> str
_, ext = path.splitext(filename.lower())
if ext in mime_suffixes:
return mime_suffixes[ext]
- elif content:
- # TODO: When the content argument is removed, make filename a required
- # argument.
- warnings.warn('The content argument of guess_mimetype() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return guess_mimetype_for_stream(BytesIO(content), default=default)
elif path.exists(filename):
with open(filename, 'rb') as f:
return guess_mimetype_for_stream(f, default=default)
diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py
index 89dd842e3..ff399c439 100644
--- a/sphinx/util/inspect.py
+++ b/sphinx/util/inspect.py
@@ -14,11 +14,9 @@ import inspect
import re
import sys
import typing
-import warnings
from functools import partial
from io import StringIO
-from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.util import logging
from sphinx.util.typing import NoneType
@@ -264,26 +262,6 @@ def is_builtin_class_method(obj, attr_name):
return getattr(builtins, safe_getattr(cls, '__name__', '')) is cls # type: ignore
-class Parameter:
- """Fake parameter class for python2."""
- POSITIONAL_ONLY = 0
- POSITIONAL_OR_KEYWORD = 1
- VAR_POSITIONAL = 2
- KEYWORD_ONLY = 3
- VAR_KEYWORD = 4
- empty = object()
-
- def __init__(self, name, kind=POSITIONAL_OR_KEYWORD, default=empty):
- # type: (str, int, Any) -> None
- self.name = name
- self.kind = kind
- self.default = default
- self.annotation = self.empty
-
- warnings.warn('sphinx.util.inspect.Parameter is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
-
-
class Signature:
"""The Signature object represents the call signature of a callable object and
its return annotation.
diff --git a/sphinx/util/osutil.py b/sphinx/util/osutil.py
index 6a070a27a..4cd646f96 100644
--- a/sphinx/util/osutil.py
+++ b/sphinx/util/osutil.py
@@ -15,12 +15,11 @@ import os
import re
import shutil
import sys
-import time
import warnings
from io import StringIO
from os import path
-from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
+from sphinx.deprecation import RemovedInSphinx40Warning
if False:
# For type annotation
@@ -148,28 +147,6 @@ def make_filename_from_project(project):
return make_filename(project_suffix_re.sub('', project)).lower()
-def ustrftime(format, *args):
- # type: (str, Any) -> str
- """[DEPRECATED] strftime for unicode strings."""
- warnings.warn('sphinx.util.osutil.ustrtime is deprecated for removal',
- RemovedInSphinx30Warning, stacklevel=2)
-
- if not args:
- # If time is not specified, try to use $SOURCE_DATE_EPOCH variable
- # See https://wiki.debian.org/ReproducibleBuilds/TimestampsProposal
- source_date_epoch = os.getenv('SOURCE_DATE_EPOCH')
- if source_date_epoch is not None:
- time_struct = time.gmtime(float(source_date_epoch))
- args = [time_struct] # type: ignore
- # On Windows, time.strftime() and Unicode characters will raise UnicodeEncodeError.
- # https://bugs.python.org/issue8304
- try:
- return time.strftime(format, *args)
- except UnicodeEncodeError:
- r = time.strftime(format.encode('unicode-escape').decode(), *args)
- return r.encode().decode('unicode-escape')
-
-
def relpath(path, start=os.curdir):
# type: (str, str) -> str
"""Return a relative filepath to *path* either from the current directory or
diff --git a/sphinx/versioning.py b/sphinx/versioning.py
index c98d166bc..56c126da2 100644
--- a/sphinx/versioning.py
+++ b/sphinx/versioning.py
@@ -9,13 +9,11 @@
:license: BSD, see LICENSE for details.
"""
import pickle
-import warnings
from itertools import product, zip_longest
from operator import itemgetter
from os import path
from uuid import uuid4
-from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.transforms import SphinxTransform
if False:
@@ -180,15 +178,6 @@ class UIDTransform(SphinxTransform):
list(merge_doctrees(old_doctree, self.document, env.versioning_condition))
-def prepare(document):
- # type: (nodes.document) -> None
- """Simple wrapper for UIDTransform."""
- warnings.warn('versioning.prepare() is deprecated. Use UIDTransform instead.',
- RemovedInSphinx30Warning, stacklevel=2)
- transform = UIDTransform(document)
- transform.apply()
-
-
def setup(app):
# type: (Sphinx) -> Dict[str, Any]
app.add_transform(UIDTransform)
diff --git a/sphinx/writers/html.py b/sphinx/writers/html.py
index 3eb9a0911..60cc7d999 100644
--- a/sphinx/writers/html.py
+++ b/sphinx/writers/html.py
@@ -11,7 +11,6 @@
import copy
import os
import posixpath
-import sys
import warnings
from typing import Iterable, cast
@@ -20,7 +19,7 @@ from docutils.writers.html4css1 import Writer, HTMLTranslator as BaseTranslator
from sphinx import addnodes
from sphinx.builders import Builder
-from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
+from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import admonitionlabels, _, __
from sphinx.util import logging
from sphinx.util.docutils import SphinxTranslator
@@ -945,33 +944,3 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator):
def unknown_visit(self, node):
# type: (nodes.Node) -> None
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)
-
- # --------- METHODS FOR COMPATIBILITY --------------------------------------
-
- @property
- def highlightlang(self):
- # type: () -> str
- warnings.warn('HTMLTranslator.highlightlang is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.builder.config.highlight_language
-
- @property
- def highlightlang_base(self):
- # type: () -> str
- warnings.warn('HTMLTranslator.highlightlang_base is deprecated.',
- RemovedInSphinx30Warning)
- return self.builder.config.highlight_language
-
- @property
- def highlightopts(self):
- # type: () -> str
- warnings.warn('HTMLTranslator.highlightopts is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.builder.config.highlight_options
-
- @property
- def highlightlinenothreshold(self):
- # type: () -> int
- warnings.warn('HTMLTranslator.highlightlinenothreshold is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return sys.maxsize
diff --git a/sphinx/writers/html5.py b/sphinx/writers/html5.py
index 646d6cc31..afab35950 100644
--- a/sphinx/writers/html5.py
+++ b/sphinx/writers/html5.py
@@ -10,7 +10,6 @@
import os
import posixpath
-import sys
import warnings
from typing import Iterable, cast
@@ -19,7 +18,7 @@ from docutils.writers.html5_polyglot import HTMLTranslator as BaseTranslator
from sphinx import addnodes
from sphinx.builders import Builder
-from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
+from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import admonitionlabels, _, __
from sphinx.util import logging
from sphinx.util.docutils import SphinxTranslator
@@ -882,33 +881,3 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
def unknown_visit(self, node):
# type: (nodes.Node) -> None
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)
-
- # --------- METHODS FOR COMPATIBILITY --------------------------------------
-
- @property
- def highlightlang(self):
- # type: () -> str
- warnings.warn('HTMLTranslator.highlightlang is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.builder.config.highlight_language
-
- @property
- def highlightlang_base(self):
- # type: () -> str
- warnings.warn('HTMLTranslator.highlightlang_base is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.builder.config.highlight_language
-
- @property
- def highlightopts(self):
- # type: () -> str
- warnings.warn('HTMLTranslator.highlightopts is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return self.builder.config.highlight_options
-
- @property
- def highlightlinenothreshold(self):
- # type: () -> int
- warnings.warn('HTMLTranslator.highlightlinenothreshold is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return sys.maxsize
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index c5be44b18..b45a95eef 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -12,7 +12,6 @@
"""
import re
-import sys
import warnings
from collections import defaultdict
from os import path
@@ -22,9 +21,7 @@ from docutils import nodes, writers
from sphinx import addnodes
from sphinx import highlighting
-from sphinx.deprecation import (
- RemovedInSphinx30Warning, RemovedInSphinx40Warning, deprecated_alias
-)
+from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.domains.std import StandardDomain
from sphinx.errors import SphinxError
from sphinx.locale import admonitionlabels, _, __
@@ -284,20 +281,6 @@ class Table:
# (cell = rectangular area)
self.cell_id = 0 # last assigned cell_id
- @property
- def caption_footnotetexts(self):
- # type: () -> List[str]
- warnings.warn('table.caption_footnotetexts is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return []
-
- @property
- def header_footnotetexts(self):
- # type: () -> List[str]
- warnings.warn('table.header_footnotetexts is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return []
-
def is_longtable(self):
# type: () -> bool
"""True if and only if table uses longtable environment."""
@@ -653,27 +636,6 @@ class LaTeXTranslator(SphinxTranslator):
self.body = self.bodystack.pop()
return body
- def restrict_footnote(self, node):
- # type: (nodes.Element) -> None
- warnings.warn('LaTeXWriter.restrict_footnote() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
-
- if self.footnote_restricted is None:
- self.footnote_restricted = node
- self.pending_footnotes = []
-
- def unrestrict_footnote(self, node):
- # type: (nodes.Element) -> None
- warnings.warn('LaTeXWriter.unrestrict_footnote() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
-
- if self.footnote_restricted == node:
- self.footnote_restricted = None
- for footnode in self.pending_footnotes:
- footnode['footnotetext'] = True
- footnode.walkabout(self)
- self.pending_footnotes = []
-
def format_docclass(self, docclass):
# type: (str) -> str
""" prepends prefix to sphinx document classes
@@ -1781,8 +1743,8 @@ class LaTeXTranslator(SphinxTranslator):
# type: (nodes.Element) -> None
self.body.append('\n\\end{flushright}\n')
- def visit_index(self, node, scre = None):
- # type: (nodes.Element, Pattern) -> None
+ def visit_index(self, node):
+ # type: (nodes.Element) -> None
def escape(value):
value = self.encode(value)
value = value.replace(r'\{', r'\sphinxleftcurlybrace{}')
@@ -1799,10 +1761,6 @@ class LaTeXTranslator(SphinxTranslator):
else:
return '\\spxentry{%s}' % string
- if scre:
- warnings.warn(('LaTeXTranslator.visit_index() optional argument '
- '"scre" is deprecated. It is ignored.'),
- RemovedInSphinx30Warning, stacklevel=2)
if not node.get('inline', True):
self.body.append('\n')
entries = node['entries']
@@ -2496,70 +2454,6 @@ class LaTeXTranslator(SphinxTranslator):
fnotes[num] = [newnode, False]
return fnotes
- @property
- def footnotestack(self):
- # type: () -> List[Dict[str, List[Union[collected_footnote, bool]]]]
- warnings.warn('LaTeXWriter.footnotestack is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return []
-
- @property
- def bibitems(self):
- # type: () -> List[List[str]]
- warnings.warn('LaTeXTranslator.bibitems() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return []
-
- @property
- def in_container_literal_block(self):
- # type: () -> int
- warnings.warn('LaTeXTranslator.in_container_literal_block is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return 0
-
- @property
- def next_section_ids(self):
- # type: () -> Set[str]
- warnings.warn('LaTeXTranslator.next_section_ids is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return set()
-
- @property
- def next_hyperlink_ids(self):
- # type: () -> Dict
- warnings.warn('LaTeXTranslator.next_hyperlink_ids is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return {}
-
- def push_hyperlink_ids(self, figtype, ids):
- # type: (str, Set[str]) -> None
- warnings.warn('LaTeXTranslator.push_hyperlink_ids() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- pass
-
- def pop_hyperlink_ids(self, figtype):
- # type: (str) -> Set[str]
- warnings.warn('LaTeXTranslator.pop_hyperlink_ids() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return set()
-
- @property
- def hlsettingstack(self):
- # type: () -> List[List[Union[str, int]]]
- warnings.warn('LaTeXTranslator.hlsettingstack is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
- return [[self.builder.config.highlight_language, sys.maxsize]]
-
- def check_latex_elements(self):
- # type: () -> None
- warnings.warn('check_latex_elements() is deprecated.',
- RemovedInSphinx30Warning, stacklevel=2)
-
- for key in self.builder.config.latex_elements:
- if key not in self.elements:
- msg = __("Unknown configure key: latex_elements[%r] is ignored.")
- logger.warning(msg % key)
-
def babel_defmacro(self, name, definition):
# type: (str, str) -> str
warnings.warn('babel_defmacro() is deprecated.',
@@ -2574,17 +2468,6 @@ class LaTeXTranslator(SphinxTranslator):
return ('%s\\def%s{%s}%s\n' % (prefix, name, definition, suffix))
- def _make_visit_admonition(name): # type: ignore
- # type: (str) -> Callable[[LaTeXTranslator, nodes.Element], None]
- warnings.warn('LaTeXTranslator._make_visit_admonition() is deprecated.',
- RemovedInSphinx30Warning)
-
- def visit_admonition(self, node):
- # type: (nodes.Element) -> None
- self.body.append('\n\\begin{sphinxadmonition}{%s}{%s:}' %
- (name, admonitionlabels[name]))
- return visit_admonition
-
def generate_numfig_format(self, builder):
# type: (LaTeXBuilder) -> str
warnings.warn('generate_numfig_format() is deprecated.',
@@ -2627,18 +2510,11 @@ class LaTeXTranslator(SphinxTranslator):
# Import old modules here for compatibility
-from sphinx.builders.latex.transforms import URI_SCHEMES, ShowUrlsTransform # NOQA
from sphinx.builders.latex.util import ExtBabel # NOQA
deprecated_alias('sphinx.writers.latex',
{
- 'ShowUrlsTransform': ShowUrlsTransform,
- 'URI_SCHEMES': URI_SCHEMES,
- },
- RemovedInSphinx30Warning)
-deprecated_alias('sphinx.writers.latex',
- {
'ExtBabel': ExtBabel,
},
RemovedInSphinx40Warning)
diff --git a/sphinx/writers/texinfo.py b/sphinx/writers/texinfo.py
index 4262ccd66..77d3dcb69 100644
--- a/sphinx/writers/texinfo.py
+++ b/sphinx/writers/texinfo.py
@@ -10,14 +10,12 @@
import re
import textwrap
-import warnings
from os import path
from typing import Iterable, cast
from docutils import nodes, writers
from sphinx import addnodes, __display_version__
-from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.errors import ExtensionError
from sphinx.locale import admonitionlabels, _, __
from sphinx.util import logging
@@ -1745,13 +1743,3 @@ class TexinfoTranslator(SphinxTranslator):
self.body.append('\n\n@example\n%s\n@end example\n\n' %
self.escape_arg(node.astext()))
raise nodes.SkipNode
-
- def _make_visit_admonition(name): # type: ignore
- # type: (str) -> Callable[[TexinfoTranslator, nodes.Element], None]
- warnings.warn('TexinfoTranslator._make_visit_admonition() is deprecated.',
- RemovedInSphinx30Warning)
-
- def visit(self, node):
- # type: (nodes.Element) -> None
- self.visit_admonition(node, admonitionlabels[name])
- return visit
diff --git a/sphinx/writers/text.py b/sphinx/writers/text.py
index 1447510c3..47ab9f2e4 100644
--- a/sphinx/writers/text.py
+++ b/sphinx/writers/text.py
@@ -11,7 +11,6 @@ import math
import os
import re
import textwrap
-import warnings
from itertools import groupby, chain
from typing import Iterable, cast
@@ -19,7 +18,6 @@ from docutils import nodes, writers
from docutils.utils import column_width
from sphinx import addnodes
-from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.locale import admonitionlabels, _
from sphinx.util.docutils import SphinxTranslator
@@ -1368,13 +1366,3 @@ class TextTranslator(SphinxTranslator):
def unknown_visit(self, node):
# type: (nodes.Node) -> None
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)
-
- def _make_depart_admonition(name): # type: ignore
- # type: (str) -> Callable[[TextTranslator, nodes.Element], None]
- warnings.warn('TextTranslator._make_depart_admonition() is deprecated.',
- RemovedInSphinx30Warning)
-
- def depart_admonition(self, node):
- # type: (nodes.Element) -> None
- self.end_state(first=admonitionlabels[name] + ': ')
- return depart_admonition
diff --git a/tests/roots/test-add_source_parser/conf.py b/tests/roots/test-add_source_parser/conf.py
index 9ff50b21e..2acd4d24c 100644
--- a/tests/roots/test-add_source_parser/conf.py
+++ b/tests/roots/test-add_source_parser/conf.py
@@ -1,17 +1,8 @@
import os
import sys
-from docutils.parsers import Parser
-
sys.path.insert(0, os.path.abspath('.'))
-class DummyMarkdownParser(Parser):
- supported = ('markdown',)
-
-
extensions = ['source_parser']
-source_suffix = ['.rst', '.md']
-source_parsers = {
- '.md': DummyMarkdownParser
-}
+source_suffix = ['.rst']
diff --git a/tests/roots/test-ext-math-compat/conf.py b/tests/roots/test-ext-math-compat/conf.py
index 30d26f97c..85e3950a5 100644
--- a/tests/roots/test-ext-math-compat/conf.py
+++ b/tests/roots/test-ext-math-compat/conf.py
@@ -1,17 +1,18 @@
+from docutils import nodes
from docutils.parsers.rst import Directive
-from sphinx.ext.mathbase import math, displaymath
-
extensions = ['sphinx.ext.mathjax']
def my_math_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
- return [math(latex='E = mc^2')], []
+ text = 'E = mc^2'
+ return [nodes.math(text, text)], []
class MyMathDirective(Directive):
def run(self):
- return [displaymath(latex='E = mc^2')]
+ text = 'E = mc^2'
+ return [nodes.math_block(text, text)]
def setup(app):
diff --git a/tests/test_application.py b/tests/test_application.py
index f10592b51..8c48e7500 100644
--- a/tests/test_application.py
+++ b/tests/test_application.py
@@ -61,20 +61,13 @@ def test_extension_in_blacklist(app, status, warning):
@pytest.mark.sphinx(testroot='add_source_parser')
-@pytest.mark.filterwarnings('ignore:The config variable "source_parsers"')
-@pytest.mark.filterwarnings('ignore:app.add_source_parser\\(\\) does not support suffix')
def test_add_source_parser(app, status, warning):
- assert set(app.config.source_suffix) == {'.rst', '.md', '.test'}
+ assert set(app.config.source_suffix) == {'.rst', '.test'}
# .rst; only in :confval:`source_suffix`
assert '.rst' not in app.registry.get_source_parsers()
assert app.registry.source_suffix['.rst'] is None
- # .md; configured by :confval:`source_suffix` and :confval:`source_parsers`
- assert '.md' in app.registry.get_source_parsers()
- assert app.registry.source_suffix['.md'] == '.md'
- assert app.registry.get_source_parsers()['.md'].__name__ == 'DummyMarkdownParser'
-
# .test; configured by API
assert app.registry.source_suffix['.test'] == 'test'
assert 'test' in app.registry.get_source_parsers()
diff --git a/tests/test_autodoc.py b/tests/test_autodoc.py
index 27412a9da..cfb62d1ba 100644
--- a/tests/test_autodoc.py
+++ b/tests/test_autodoc.py
@@ -16,10 +16,7 @@ from warnings import catch_warnings
import pytest
from docutils.statemachine import ViewList
-from sphinx.ext.autodoc import (
- ModuleLevelDocumenter, cut_lines, between, ALL,
- merge_autodoc_default_flags, Options
-)
+from sphinx.ext.autodoc import ModuleLevelDocumenter, cut_lines, between, ALL, Options
from sphinx.ext.autodoc.directive import DocumenterBridge, process_documenter_options
from sphinx.testing.util import SphinxTestApp, Struct # NOQA
from sphinx.util import logging
@@ -1523,27 +1520,6 @@ def test_partialmethod(app):
@pytest.mark.sphinx('html', testroot='ext-autodoc')
-@pytest.mark.filterwarnings('ignore:autodoc_default_flags is now deprecated.')
-def test_merge_autodoc_default_flags1(app):
- app.config.autodoc_default_flags = ['members', 'undoc-members']
- merge_autodoc_default_flags(app, app.config)
- assert app.config.autodoc_default_options == {'members': None,
- 'undoc-members': None}
-
-
-@pytest.mark.sphinx('html', testroot='ext-autodoc')
-@pytest.mark.filterwarnings('ignore:autodoc_default_flags is now deprecated.')
-def test_merge_autodoc_default_flags2(app):
- app.config.autodoc_default_flags = ['members', 'undoc-members']
- app.config.autodoc_default_options = {'members': 'this,that,order',
- 'inherited-members': 'this'}
- merge_autodoc_default_flags(app, app.config)
- assert app.config.autodoc_default_options == {'members': None,
- 'undoc-members': None,
- 'inherited-members': 'this'}
-
-
-@pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_autodoc_default_options(app):
# no settings
actual = do_autodoc(app, 'class', 'target.enum.EnumCls')
diff --git a/tests/test_ext_autodoc_mock.py b/tests/test_ext_autodoc_mock.py
index 767232bcc..79a2782d3 100644
--- a/tests/test_ext_autodoc_mock.py
+++ b/tests/test_ext_autodoc_mock.py
@@ -17,7 +17,7 @@ from sphinx.ext.autodoc.mock import _MockModule, _MockObject, mock
def test_MockModule():
- mock = _MockModule('mocked_module', None)
+ mock = _MockModule('mocked_module')
assert isinstance(mock.some_attr, _MockObject)
assert isinstance(mock.some_method, _MockObject)
assert isinstance(mock.attr1.attr2, _MockObject)
diff --git a/tests/test_util_images.py b/tests/test_util_images.py
index 5e0f2801c..dbe155035 100644
--- a/tests/test_util_images.py
+++ b/tests/test_util_images.py
@@ -20,20 +20,15 @@ PDF_FILENAME = 'img.pdf'
TXT_FILENAME = 'index.txt'
-@pytest.fixture(scope='module')
-def testroot(rootdir):
- return rootdir / 'test-root'
-
-
-def test_get_image_size(testroot):
- assert get_image_size(testroot / GIF_FILENAME) == (200, 181)
- assert get_image_size(testroot / PNG_FILENAME) == (200, 181)
- assert get_image_size(testroot / PDF_FILENAME) is None
- assert get_image_size(testroot / TXT_FILENAME) is None
+def test_get_image_size(rootdir):
+ assert get_image_size(rootdir / 'test-root' / GIF_FILENAME) == (200, 181)
+ assert get_image_size(rootdir / 'test-root' / PNG_FILENAME) == (200, 181)
+ assert get_image_size(rootdir / 'test-root' / PDF_FILENAME) is None
+ assert get_image_size(rootdir / 'test-root' / TXT_FILENAME) is None
@pytest.mark.filterwarnings('ignore:The content argument')
-def test_guess_mimetype(testroot):
+def test_guess_mimetype():
# guess by filename
assert guess_mimetype('img.png') == 'image/png'
assert guess_mimetype('img.jpg') == 'image/jpeg'
@@ -42,24 +37,9 @@ def test_guess_mimetype(testroot):
assert guess_mimetype('no_extension') is None
assert guess_mimetype('IMG.PNG') == 'image/png'
- # guess by content
- assert guess_mimetype(content=(testroot / GIF_FILENAME).bytes()) == 'image/gif'
- assert guess_mimetype(content=(testroot / PNG_FILENAME).bytes()) == 'image/png'
- assert guess_mimetype(content=(testroot / PDF_FILENAME).bytes()) is None
- assert guess_mimetype(content=(testroot / TXT_FILENAME).bytes()) is None
- assert guess_mimetype(content=(testroot / TXT_FILENAME).bytes(),
- default='text/plain') == 'text/plain'
-
- # the priority of params: filename > content > default
- assert guess_mimetype('img.png',
- content=(testroot / GIF_FILENAME).bytes(),
- default='text/plain') == 'image/png'
- assert guess_mimetype('no_extension',
- content=(testroot / GIF_FILENAME).bytes(),
- default='text/plain') == 'image/gif'
- assert guess_mimetype('no_extension',
- content=(testroot / TXT_FILENAME).bytes(),
- default='text/plain') == 'text/plain'
+ # default parameter is used when no extension
+ assert guess_mimetype('img.png', 'text/plain') == 'image/png'
+ assert guess_mimetype('no_extension', 'text/plain') == 'text/plain'
def test_get_image_extension():