Skip to content

Commit

Permalink
Merge pull request sphinx-doc#9966 from tk0miya/RemovedInSphinx50Warning
Browse files Browse the repository at this point in the history
refactor: Remove RemovedInSphinx50Warning (partially)
  • Loading branch information
tk0miya committed Dec 17, 2021
2 parents 5dc27f5 + 1233d05 commit eb1a8a3
Show file tree
Hide file tree
Showing 13 changed files with 18 additions and 281 deletions.
14 changes: 0 additions & 14 deletions sphinx/builders/latex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
"""

import os
import warnings
from os import path
from typing import Any, Dict, Iterable, List, Tuple, Union

Expand All @@ -24,7 +23,6 @@
from sphinx.builders.latex.theming import Theme, ThemeFactory
from sphinx.builders.latex.util import ExtBabel
from sphinx.config import ENUM, Config
from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.environment.adapters.asset import ImageAdapter
from sphinx.errors import NoUri, SphinxError
from sphinx.locale import _, __
Expand Down Expand Up @@ -449,18 +447,6 @@ def write_message_catalog(self) -> None:
filename = path.join(package_dir, 'templates', 'latex', 'sphinxmessages.sty_t')
copy_asset_file(filename, self.outdir, context=context, renderer=LaTeXRenderer())

@property
def usepackages(self) -> List[Tuple[str, str]]:
warnings.warn('LaTeXBuilder.usepackages is deprecated.',
RemovedInSphinx50Warning, stacklevel=2)
return self.app.registry.latex_packages

@property
def usepackages_after_hyperref(self) -> List[Tuple[str, str]]:
warnings.warn('LaTeXBuilder.usepackages_after_hyperref is deprecated.',
RemovedInSphinx50Warning, stacklevel=2)
return self.app.registry.latex_packages_after_hyperref


def validate_config_values(app: Sphinx, config: Config) -> None:
for key in list(config.latex_elements):
Expand Down
11 changes: 0 additions & 11 deletions sphinx/directives/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

from sphinx import addnodes
from sphinx.addnodes import desc_signature
from sphinx.deprecation import RemovedInSphinx50Warning, deprecated_alias
from sphinx.util import docutils
from sphinx.util.docfields import DocFieldTransformer, Field, TypedField
from sphinx.util.docutils import SphinxDirective
Expand Down Expand Up @@ -266,16 +265,6 @@ def run(self) -> List[Node]:
return []


deprecated_alias('sphinx.directives',
{
'DescDirective': ObjectDescription,
},
RemovedInSphinx50Warning,
{
'DescDirective': 'sphinx.directives.ObjectDescription',
})


def setup(app: "Sphinx") -> Dict[str, Any]:
app.add_config_value("strip_signature_backslash", False, 'env')
directives.register_directive('default-role', DefaultRole)
Expand Down
6 changes: 3 additions & 3 deletions sphinx/domains/c.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from sphinx.addnodes import pending_xref
from sphinx.application import Sphinx
from sphinx.builders import Builder
from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.deprecation import RemovedInSphinx60Warning
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType
from sphinx.environment import BuildEnvironment
Expand Down Expand Up @@ -3276,7 +3276,7 @@ def handle_signature(self, sig: str, signode: TextElement) -> ASTDeclaration:
msg = "{}: Pre-v3 C type directive '.. c:type:: {}' converted to " \
"'.. c:{}:: {}'." \
"\nThe original parsing error was:\n{}"
msg = msg.format(RemovedInSphinx50Warning.__name__,
msg = msg.format(RemovedInSphinx60Warning.__name__,
sig, ast.objectType, ast, eOrig)
logger.warning(msg, location=signode)
except DefinitionError as e:
Expand Down Expand Up @@ -3710,7 +3710,7 @@ def run(self) -> Tuple[List[Node], List[system_message]]:
if self.env.config['c_warn_on_allowed_pre_v3']:
msg = "{}: Pre-v3 C type role ':c:type:`{}`' converted to ':c:expr:`{}`'."
msg += "\nThe original parsing error was:\n{}"
msg = msg.format(RemovedInSphinx50Warning.__name__, text, text, eOrig)
msg = msg.format(RemovedInSphinx60Warning.__name__, text, text, eOrig)
logger.warning(msg, location=self.get_location())
return [signode], []

Expand Down
31 changes: 2 additions & 29 deletions sphinx/domains/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from sphinx.addnodes import desc_signature, pending_xref, pending_xref_condition
from sphinx.application import Sphinx
from sphinx.builders import Builder
from sphinx.deprecation import RemovedInSphinx50Warning, RemovedInSphinx60Warning
from sphinx.deprecation import RemovedInSphinx60Warning
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, Index, IndexEntry, ObjType
from sphinx.environment import BuildEnvironment
Expand Down Expand Up @@ -122,7 +122,7 @@ def type_to_xref(target: str, env: BuildEnvironment = None, suppress_prefix: boo
refspecific=refspecific, **kwargs)


def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Node]:
def _parse_annotation(annotation: str, env: BuildEnvironment) -> List[Node]:
"""Parse type annotation."""
def unparse(node: ast.AST) -> List[Node]:
if isinstance(node, ast.Attribute):
Expand Down Expand Up @@ -210,10 +210,6 @@ def unparse(node: ast.AST) -> List[Node]:

raise SyntaxError # unsupported syntax

if env is None:
warnings.warn("The env parameter for _parse_annotation becomes required now.",
RemovedInSphinx50Warning, stacklevel=2)

try:
tree = ast_parse(annotation)
result: List[Node] = []
Expand Down Expand Up @@ -979,29 +975,6 @@ def get_index_text(self, modname: str, name_cls: Tuple[str, str]) -> str:
return _('%s (%s property)') % (attrname, clsname)


class PyDecoratorMixin:
"""
Mixin for decorator directives.
"""
def handle_signature(self, sig: str, signode: desc_signature) -> Tuple[str, str]:
for cls in self.__class__.__mro__:
if cls.__name__ != 'DirectiveAdapter':
warnings.warn('PyDecoratorMixin is deprecated. '
'Please check the implementation of %s' % cls,
RemovedInSphinx50Warning, stacklevel=2)
break
else:
warnings.warn('PyDecoratorMixin is deprecated',
RemovedInSphinx50Warning, stacklevel=2)

ret = super().handle_signature(sig, signode) # type: ignore
signode.insert(0, addnodes.desc_addname('@', '@'))
return ret

def needs_arglist(self) -> bool:
return False


class PyModule(SphinxDirective):
"""
Directive to mark description of a new module.
Expand Down
7 changes: 0 additions & 7 deletions sphinx/domains/std.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

import re
import unicodedata
import warnings
from copy import copy
from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional,
Tuple, Type, Union, cast)
Expand All @@ -22,7 +21,6 @@

from sphinx import addnodes
from sphinx.addnodes import desc_signature, pending_xref
from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType
from sphinx.locale import _, __
Expand Down Expand Up @@ -675,11 +673,6 @@ def note_object(self, objtype: str, name: str, labelid: str, location: Any = Non
objtype, name, docname, location=location)
self.objects[objtype, name] = (self.env.docname, labelid)

def add_object(self, objtype: str, name: str, docname: str, labelid: str) -> None:
warnings.warn('StandardDomain.add_object() is deprecated.',
RemovedInSphinx50Warning, stacklevel=2)
self.objects[objtype, name] = (docname, labelid)

@property
def _terms(self) -> Dict[str, Tuple[str, str]]:
""".. note:: Will be removed soon. internal use only."""
Expand Down
30 changes: 1 addition & 29 deletions sphinx/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import tempfile
import traceback
import unicodedata
import warnings
from datetime import datetime
from importlib import import_module
from os import path
Expand All @@ -26,7 +25,6 @@
Pattern, Set, Tuple, Type)
from urllib.parse import parse_qsl, quote_plus, urlencode, urlsplit, urlunsplit

from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.errors import ExtensionError, FiletypeNotFoundError, SphinxParallelError
from sphinx.locale import __
from sphinx.util import logging
Expand All @@ -37,7 +35,7 @@
# import other utilities; partly for backwards compatibility, so don't
# prune unused ones indiscriminately
from sphinx.util.osutil import (SEP, copyfile, copytimes, ensuredir, make_filename, # noqa
movefile, mtimes_of_files, os_path, relative_uri)
mtimes_of_files, os_path, relative_uri)
from sphinx.util.typing import PathMatcher

if TYPE_CHECKING:
Expand Down Expand Up @@ -337,32 +335,6 @@ def parselinenos(spec: str, total: int) -> List[int]:
return items


def force_decode(string: str, encoding: str) -> str:
"""Forcibly get a unicode string out of a bytestring."""
warnings.warn('force_decode() is deprecated.',
RemovedInSphinx50Warning, stacklevel=2)
if isinstance(string, bytes):
try:
if encoding:
string = string.decode(encoding)
else:
# try decoding with utf-8, should only work for real UTF-8
string = string.decode()
except UnicodeError:
# last resort -- can't fail
string = string.decode('latin1')
return string


def rpartition(s: str, t: str) -> Tuple[str, str]:
"""Similar to str.rpartition from 2.5, but doesn't return the separator."""
warnings.warn('rpartition() is now deprecated.', RemovedInSphinx50Warning, stacklevel=2)
i = s.rfind(t)
if i != -1:
return s[:i], s[i + len(t):]
return '', s


def split_into(n: int, type: str, value: str) -> List[str]:
"""Split an index entry into a given number of parts at semicolons."""
parts = [x.strip() for x in value.split(';', n - 1)]
Expand Down
78 changes: 3 additions & 75 deletions sphinx/util/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,13 @@
import sys
import types
import typing
import warnings
from functools import partial, partialmethod
from importlib import import_module
from inspect import Parameter, isclass, ismethod, ismethoddescriptor, ismodule # NOQA
from io import StringIO
from types import ModuleType
from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Tuple, Type, cast

from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.pycode.ast import ast # for py36-37
from sphinx.pycode.ast import unparse as ast_unparse
from sphinx.util import logging
Expand All @@ -47,69 +45,6 @@
memory_address_re = re.compile(r' at 0x[0-9a-f]{8,16}(?=>)', re.IGNORECASE)


# Copied from the definition of inspect.getfullargspec from Python master,
# and modified to remove the use of special flags that break decorated
# callables and bound methods in the name of backwards compatibility. Used
# under the terms of PSF license v2, which requires the above statement
# and the following:
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
# 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Python Software
# Foundation; All Rights Reserved
def getargspec(func: Callable) -> Any:
"""Like inspect.getfullargspec but supports bound methods, and wrapped
methods."""
warnings.warn('sphinx.ext.inspect.getargspec() is deprecated',
RemovedInSphinx50Warning, stacklevel=2)

sig = inspect.signature(func)

args = []
varargs = None
varkw = None
kwonlyargs = []
defaults = ()
annotations = {}
defaults = ()
kwdefaults = {}

if sig.return_annotation is not sig.empty:
annotations['return'] = sig.return_annotation

for param in sig.parameters.values():
kind = param.kind
name = param.name

if kind is Parameter.POSITIONAL_ONLY:
args.append(name)
elif kind is Parameter.POSITIONAL_OR_KEYWORD:
args.append(name)
if param.default is not param.empty:
defaults += (param.default,) # type: ignore
elif kind is Parameter.VAR_POSITIONAL:
varargs = name
elif kind is Parameter.KEYWORD_ONLY:
kwonlyargs.append(name)
if param.default is not param.empty:
kwdefaults[name] = param.default
elif kind is Parameter.VAR_KEYWORD:
varkw = name

if param.annotation is not param.empty:
annotations[name] = param.annotation

if not kwdefaults:
# compatibility with 'func.__kwdefaults__'
kwdefaults = None

if not defaults:
# compatibility with 'func.__defaults__'
defaults = None

return inspect.FullArgSpec(args, varargs, varkw, defaults,
kwonlyargs, kwdefaults, annotations)


def unwrap(obj: Any) -> Any:
"""Get an original object from wrapped object (wrapped functions)."""
try:
Expand Down Expand Up @@ -623,26 +558,19 @@ def _should_unwrap(subject: Callable) -> bool:
return False


def signature(subject: Callable, bound_method: bool = False, follow_wrapped: bool = None,
type_aliases: Dict = {}) -> inspect.Signature:
def signature(subject: Callable, bound_method: bool = False, type_aliases: Dict = {}
) -> inspect.Signature:
"""Return a Signature object for the given *subject*.
:param bound_method: Specify *subject* is a bound method or not
:param follow_wrapped: Same as ``inspect.signature()``.
"""

if follow_wrapped is None:
follow_wrapped = True
else:
warnings.warn('The follow_wrapped argument of sphinx.util.inspect.signature() is '
'deprecated', RemovedInSphinx50Warning, stacklevel=2)

try:
try:
if _should_unwrap(subject):
signature = inspect.signature(subject)
else:
signature = inspect.signature(subject, follow_wrapped=follow_wrapped)
signature = inspect.signature(subject, follow_wrapped=True)
except ValueError:
# follow built-in wrappers up (ex. functools.lru_cache)
signature = inspect.signature(subject)
Expand Down
16 changes: 0 additions & 16 deletions sphinx/util/osutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,10 @@
import re
import shutil
import sys
import warnings
from io import StringIO
from os import path
from typing import Any, Generator, Iterator, List, Optional, Type

from sphinx.deprecation import RemovedInSphinx50Warning

try:
# for ALT Linux (#6712)
from sphinx.testing.path import path as Path
Expand Down Expand Up @@ -84,19 +81,6 @@ def mtimes_of_files(dirnames: List[str], suffix: str) -> Iterator[float]:
pass


def movefile(source: str, dest: str) -> None:
"""Move a file, removing the destination if it exists."""
warnings.warn('sphinx.util.osutil.movefile() is deprecated for removal. '
'Please use os.replace() instead.',
RemovedInSphinx50Warning, stacklevel=2)
if os.path.exists(dest):
try:
os.unlink(dest)
except OSError:
pass
os.rename(source, dest)


def copytimes(source: str, dest: str) -> None:
"""Copy a file's modification times."""
st = os.stat(source)
Expand Down

0 comments on commit eb1a8a3

Please sign in to comment.