Merge branch '2.0' into 2155_code_directive

This commit is contained in:
Takeshi KOMIYA
2019-03-10 12:05:26 +09:00
committed by GitHub
79 changed files with 273 additions and 152 deletions

View File

@@ -6,6 +6,6 @@ jobs:
working_directory: /sphinx
steps:
- checkout
- run: /python3.5/bin/pip install -U pip setuptools
- run: /python3.5/bin/pip install -U .[test,websupport]
- run: make test PYTHON=/python3.5/bin/python
- run: /python3.6/bin/pip install -U pip setuptools
- run: /python3.6/bin/pip install -U .[test,websupport]
- run: make test PYTHON=/python3.6/bin/python

11
CHANGES
View File

@@ -7,6 +7,8 @@ Dependencies
Incompatible changes
--------------------
* texinfo: image files are copied into ``name-figure`` directory
Deprecated
----------
@@ -22,6 +24,12 @@ Bugs fixed
* #5508: ``linenothreshold`` option for ``highlight`` directive was ignored
* texinfo: ``make install-info`` causes syntax error
* texinfo: ``make install-info`` fails on macOS
* #3079: texinfo: image files are not copied on ``make install-info``
* #5391: A cross reference in heading is rendered as literal
* #5946: C++, fix ``cpp:alias`` problems in LaTeX (and singlehtml)
* #6147: classes attribute of ``citation_reference`` node is lost
* AssertionError is raised when custom ``citation_reference`` node having
classes attribute refers missing citation (refs: #6147)
* #2155: Support ``code`` directive
Testing
@@ -296,6 +304,9 @@ Bugs fixed
* #6047: autodoc: ``autofunction`` emits a warning for method objects
* #6028: graphviz: Ensure the graphviz filenames are reproducible
* #6068: doctest: ``skipif`` option may remove the code block from documentation
* #6136: ``:name:`` option for ``math`` directive causes a crash
* #6139: intersphinx: ValueError on failure reporting
* #6135: changes: Fix UnboundLocalError when any module found
Testing
--------

View File

@@ -1294,8 +1294,6 @@ The JavaScript domain (name **js**) provides the following directives:
specified. If this option is specified, the directive will only update the
current module name.
To clear the current module, set the module name to ``null`` or ``None``
.. versionadded:: 1.6
.. rst:directive:: .. js:function:: name(signature)

View File

@@ -39,7 +39,6 @@ extras_require = {
'colorama>=0.3.5',
],
'test': [
'mock',
'pytest',
'pytest-cov',
'html5lib',

View File

@@ -40,7 +40,7 @@ except ImportError:
if False:
# For type annotation
from typing import Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple, Type, Union # NOQA
from typing import Any, Dict, Iterable, List, Sequence, Set, Tuple, Type, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@@ -36,7 +36,6 @@ except ImportError:
if False:
# For type annotation
from typing import Any, Dict, List, Set, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
logger = logging.getLogger(__name__)

View File

@@ -83,8 +83,7 @@ class ChangesBuilder(Builder):
entry = '<b>%s</b>: <i>%s</i>.' % (descname, ttext)
apichanges.append((entry, changeset.docname, changeset.lineno))
elif descname or changeset.module:
if not changeset.module:
module = _('Builtins')
module = changeset.module or _('Builtins')
if not descname:
descname = _('Module level')
if context:

View File

@@ -25,8 +25,7 @@ from sphinx.util.osutil import make_filename
if False:
# For type annotation
from typing import Any, Dict, Iterable, List, Set, Tuple # NOQA
from docutils import nodes # NOQA
from typing import Any, Dict, List, Set, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA

View File

@@ -40,9 +40,11 @@ from sphinx.writers.latex import (
ADDITIONAL_SETTINGS, DEFAULT_SETTINGS, LaTeXWriter, LaTeXTranslator
)
# load docutils.nodes after loading sphinx.builders.latex.nodes
from docutils import nodes # NOQA
if False:
# For type annotation
from docutils import nodes # NOQA
from typing import Any, Dict, Iterable, List, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA
@@ -295,7 +297,6 @@ class LaTeXBuilder(Builder):
def assemble_doctree(self, indexfile, toctree_only, appendices):
# type: (str, bool, List[str]) -> nodes.document
from docutils import nodes # NOQA
self.docnames = set([indexfile] + appendices)
logger.info(darkgreen(indexfile) + " ", nonl=True)
tree = self.env.get_doctree(indexfile)

View File

@@ -21,7 +21,7 @@ from sphinx.util.nodes import NodeMatcher
if False:
# For type annotation
from typing import Any, Dict, List, Set, Tuple, Union # NOQA
from typing import Any, List, Set, Tuple # NOQA
URI_SCHEMES = ('mailto:', 'http:', 'https:', 'ftp:')

View File

@@ -30,7 +30,7 @@ from sphinx.util.requests import is_ssl_error
if False:
# For type annotation
from typing import Any, Dict, List, Set, Tuple, Union # NOQA
from typing import Any, Dict, List, Set, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.util.requests.requests import Response # NOQA

View File

@@ -27,7 +27,7 @@ from sphinx.util.console import darkgreen # type: ignore
from sphinx.util.docutils import new_document
from sphinx.util.fileutil import copy_asset_file
from sphinx.util.nodes import inline_all_toctrees
from sphinx.util.osutil import SEP, make_filename_from_project
from sphinx.util.osutil import SEP, ensuredir, make_filename_from_project
from sphinx.writers.texinfo import TexinfoWriter, TexinfoTranslator
if False:
@@ -134,6 +134,7 @@ class TexinfoBuilder(Builder):
settings.docname = docname
doctree.settings = settings
docwriter.write(doctree, destination)
self.copy_image_files(targetname[:-5])
def assemble_doctree(self, indexfile, toctree_only, appendices):
# type: (str, bool, List[str]) -> nodes.document
@@ -180,11 +181,10 @@ class TexinfoBuilder(Builder):
def finish(self):
# type: () -> None
self.copy_image_files()
self.copy_support_files()
def copy_image_files(self):
# type: () -> None
def copy_image_files(self, targetname):
# type: (str) -> None
if self.images:
stringify_func = ImageAdapter(self.app.env).get_original_image_uri
for src in status_iterator(self.images, __('copying images... '), "brown",
@@ -192,8 +192,9 @@ class TexinfoBuilder(Builder):
stringify_func=stringify_func):
dest = self.images[src]
try:
copy_asset_file(path.join(self.srcdir, src),
path.join(self.outdir, dest))
imagedir = path.join(self.outdir, targetname + '-figures')
ensuredir(imagedir)
copy_asset_file(path.join(self.srcdir, dest), imagedir)
except Exception as err:
logger.warning(__('cannot copy image file %r: %s'),
path.join(self.srcdir, src), err)

View File

@@ -27,7 +27,7 @@ from sphinx.util.typing import NoneType
if False:
# For type annotation
from typing import Any, Callable, Dict, Generator, Iterator, List, Set, Tuple, Union # NOQA
from typing import Callable, Dict, Generator, Iterator, List, Set, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA
from sphinx.util.tags import Tags # NOQA

View File

@@ -23,8 +23,6 @@ if False:
# For type annotation
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA
from sphinx.environment import BuildEnvironment # NOQA
from sphinx.util.docfields import Field # NOQA
from sphinx.util.typing import DirectiveOption # NOQA

View File

@@ -26,7 +26,7 @@ from sphinx.util.nodes import explicit_title_re, set_source_info, \
if False:
# For type annotation
from typing import Any, Dict, Generator, List, Tuple # NOQA
from typing import Any, Dict, List # NOQA
from sphinx.application import Sphinx # NOQA

View File

@@ -173,13 +173,16 @@ class MathDirective(SphinxDirective):
latex = '\n'.join(self.content)
if self.arguments and self.arguments[0]:
latex = self.arguments[0] + '\n\n' + latex
label = self.options.get('label', self.options.get('name'))
node = nodes.math_block(latex, latex,
docname=self.env.docname,
number=self.options.get('name'),
label=self.options.get('label'),
number=None,
label=label,
nowrap='nowrap' in self.options)
ret = [node] # type: List[nodes.Node]
self.add_name(node)
set_source_info(self, node)
ret = [node] # type: List[nodes.Node]
self.add_target(ret)
return ret

View File

@@ -6734,27 +6734,20 @@ class CPPNamespacePopObject(SphinxDirective):
class AliasNode(nodes.Element):
def __init__(self, sig, warnEnv):
"""
:param sig: The name or function signature to alias.
:param warnEnv: An object which must have the following attributes:
env: a Sphinx environment
whatever DefinitionParser requires of warnEnv
"""
def __init__(self, sig, env=None, parentKey=None):
super().__init__()
self.sig = sig
env = warnEnv.env
if 'cpp:parent_symbol' not in env.temp_data:
root = env.domaindata['cpp']['root_symbol']
env.temp_data['cpp:parent_symbol'] = root
self.parentKey = env.temp_data['cpp:parent_symbol'].get_lookup_key()
try:
parser = DefinitionParser(sig, warnEnv, warnEnv.env.config)
self.ast, self.isShorthand = parser.parse_xref_object()
parser.assert_end()
except DefinitionError as e:
warnEnv.warn(e)
self.ast = None
if env is not None:
if 'cpp:parent_symbol' not in env.temp_data:
root = env.domaindata['cpp']['root_symbol']
env.temp_data['cpp:parent_symbol'] = root
self.parentKey = env.temp_data['cpp:parent_symbol'].get_lookup_key()
else:
assert parentKey is not None
self.parentKey = parentKey
def copy(self):
return self.__class__(self.sig, env=None, parentKey=self.parentKey)
class AliasTransform(SphinxTransform):
@@ -6763,8 +6756,20 @@ class AliasTransform(SphinxTransform):
def apply(self, **kwargs):
# type: (Any) -> None
for node in self.document.traverse(AliasNode):
class Warner:
def warn(self, msg):
logger.warning(msg, location=node)
warner = Warner()
sig = node.sig
ast = node.ast
parentKey = node.parentKey
try:
parser = DefinitionParser(sig, warner, self.env.config)
ast, isShorthand = parser.parse_xref_object()
parser.assert_end()
except DefinitionError as e:
warner.warn(e)
ast, isShorthand = None, None
if ast is None:
# could not be parsed, so stop here
signode = addnodes.desc_signature(sig, '')
@@ -6774,8 +6779,6 @@ class AliasTransform(SphinxTransform):
node.replace_self(signode)
continue
isShorthand = node.isShorthand
parentKey = node.parentKey
rootSymbol = self.env.domains['cpp'].data['root_symbol']
parentSymbol = rootSymbol.direct_lookup(parentKey)
if not parentSymbol:
@@ -6833,10 +6836,6 @@ class AliasTransform(SphinxTransform):
class CPPAliasObject(ObjectDescription):
option_spec = {} # type: Dict
def warn(self, msg):
# type: (Union[str, Exception]) -> None
self.state_machine.reporter.warning(msg, line=self.lineno)
def run(self):
# type: () -> List[nodes.Node]
"""
@@ -6859,7 +6858,7 @@ class CPPAliasObject(ObjectDescription):
self.names = [] # type: List[str]
signatures = self.get_signatures()
for i, sig in enumerate(signatures):
node.append(AliasNode(sig, self))
node.append(AliasNode(sig, env=self.env))
contentnode = addnodes.desc_content()
node.append(contentnode)

View File

@@ -24,7 +24,6 @@ from sphinx.util.nodes import make_refnode
if False:
# For type annotation
from typing import Any, Dict, Iterator, List, Tuple # NOQA
from docutils import nodes # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@@ -20,7 +20,7 @@ from sphinx.util.nodes import make_refnode
if False:
# For type annotation
from typing import Any, Callable, Dict, Iterable, List, Tuple, Type, Union # NOQA
from typing import Any, Dict, Iterable, List, Tuple # NOQA
from sphinx import addnodes # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA

View File

@@ -26,7 +26,7 @@ from sphinx.util.nodes import make_refnode
if False:
# For type annotation
from typing import Any, Dict, Iterable, Iterator, List, Tuple, Type, Union # NOQA
from typing import Any, Dict, Iterable, Iterator, List, Tuple, Type # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@@ -30,7 +30,7 @@ from sphinx.util.nodes import is_translatable
if False:
# For type annotation
from typing import Any, Callable, Dict, IO, Iterator, List, Optional, Pattern, Set, Tuple, Type, Union, Generator # NOQA
from typing import Any, Callable, Dict, IO, Iterator, List, Optional, Set, Tuple, Union # NOQA
from docutils import nodes # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA

View File

@@ -24,8 +24,7 @@ from sphinx.util.images import guess_mimetype
if False:
# For type annotation
from typing import Dict, List, Set, Tuple # NOQA
from docutils import nodes # NOQA
from typing import Dict, List, Set # NOQA
from sphinx.sphinx import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@@ -17,7 +17,6 @@ from sphinx.environment.collectors import EnvironmentCollector
if False:
# For type annotation
from typing import Dict, Set # NOQA
from docutils import nodes # NOQA
from sphinx.sphinx import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@@ -16,7 +16,6 @@ from sphinx.transforms import SphinxContentsFilter
if False:
# For type annotation
from typing import Dict, Set # NOQA
from docutils import nodes # NOQA
from sphinx.sphinx import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@@ -21,9 +21,8 @@ from sphinx.util import url_re, logging
if False:
# For type annotation
from typing import Any, Dict, List, Set, Tuple, Type, TypeVar # NOQA
from typing import Dict, List, Set, Tuple, Type, TypeVar # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.environment import BuildEnvironment # NOQA
N = TypeVar('N')

View File

@@ -33,9 +33,7 @@ from sphinx.util.inspect import Signature, isdescriptor, safe_getmembers, \
if False:
# For type annotation
from types import ModuleType # NOQA
from typing import Any, Callable, Dict, Iterator, List, Sequence, Set, Tuple, Type, Union # NOQA
from docutils import nodes # NOQA
from docutils.utils import Reporter # NOQA
from typing import Callable, Dict, Iterator, List, Sequence, Set, Tuple, Type, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@@ -17,9 +17,8 @@ from sphinx.util.nodes import nested_parse_with_titles
if False:
# For type annotation
from typing import Any, Callable, Dict, List, Set, Type # NOQA
from typing import Callable, Dict, List, Set, Type # NOQA
from docutils.parsers.rst.state import RSTState # NOQA
from docutils.statemachine import StateMachine, StringList # NOQA
from docutils.utils import Reporter # NOQA
from sphinx.config import Config # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@@ -24,7 +24,7 @@ from sphinx.util.inspect import isenumclass, safe_getattr
if False:
# For type annotation
from typing import Any, Callable, Dict, Generator, Iterator, List, Optional, Sequence, Tuple, Union # NOQA
from typing import Any, Callable, Dict, Generator, Iterator, List, Sequence, Tuple, Union # NOQA
logger = logging.getLogger(__name__)

View File

@@ -24,11 +24,6 @@ if False:
logger = logging.getLogger(__name__)
if False:
# For type annotation
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA
def get_node_depth(node):
i = 0

View File

@@ -41,9 +41,7 @@ from sphinx.util.rst import escape as rst_escape
if False:
# For type annotation
from typing import Any, Callable, Dict, List, Tuple, Type, Union # NOQA
from sphinx import addnodes # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.environment import BuildEnvironment # NOQA
from sphinx.ext.autodoc import Documenter # NOQA

View File

@@ -23,7 +23,7 @@ from sphinx.util.inspect import safe_getattr
if False:
# For type annotation
from typing import Any, Callable, Dict, IO, List, Pattern, Set, Tuple # NOQA
from typing import Any, Dict, IO, List, Pattern, Set, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
logger = logging.getLogger(__name__)

View File

@@ -34,7 +34,7 @@ from sphinx.util.osutil import relpath
if False:
# For type annotation
from typing import Any, Callable, Dict, IO, Iterable, List, Optional, Sequence, Set, Tuple, Type # NOQA
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Type # NOQA
from sphinx.application import Sphinx # NOQA
logger = logging.getLogger(__name__)

View File

@@ -31,7 +31,6 @@ from sphinx.util.png import read_png_depth, write_png_depth
if False:
# For type annotation
from typing import Any, Dict, List, Tuple, Union # NOQA
from sphinx.addnodes import displaymath # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.config import Config # NOQA

View File

@@ -55,7 +55,7 @@ from sphinx.util.docutils import SphinxDirective
if False:
# For type annotation
from typing import Any, Dict, List, Tuple, Dict, Optional # NOQA
from typing import Any, Dict, List, Optional, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA
from sphinx.writers.html import HTMLTranslator # NOQA

View File

@@ -41,7 +41,7 @@ from sphinx.util.inventory import InventoryFile
if False:
# For type annotation
from typing import Any, Dict, IO, List, Tuple, Union # NOQA
from typing import Any, Dict, IO, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA
from sphinx.environment import BuildEnvironment # NOQA
@@ -173,7 +173,7 @@ def fetch_inventory(app, uri, inv):
f = open(path.join(app.srcdir, inv), 'rb')
except Exception as err:
err.args = ('intersphinx inventory %r not fetchable due to %s: %s',
inv, err.__class__, err)
inv, err.__class__, str(err))
raise
try:
if hasattr(f, 'url'):
@@ -191,7 +191,7 @@ def fetch_inventory(app, uri, inv):
raise ValueError('unknown or unsupported inventory version: %r' % exc)
except Exception as err:
err.args = ('intersphinx inventory %r not readable due to %s: %s',
inv, err.__class__.__name__, err)
inv, err.__class__.__name__, str(err))
raise
else:
return invdata
@@ -234,10 +234,9 @@ def load_mappings(app):
for fail in failures:
logger.info(*fail)
else:
issues = '\n'.join([f[0] % f[1:] for f in failures])
logger.warning(__("failed to reach any of the inventories "
"with the following issues:"))
for fail in failures:
logger.warning(*fail)
"with the following issues:") + "\n" + issues)
if update:
inventories.clear()

View File

@@ -22,7 +22,7 @@ from sphinx.domains.math import MathReferenceRole as EqXRefRole # NOQA # to ke
if False:
# For type annotation
from typing import Any, Callable, List, Tuple # NOQA
from typing import Callable, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.writers.html import HTMLTranslator # NOQA

View File

@@ -14,7 +14,7 @@ import warnings
from pygments import highlight
from pygments.filters import ErrorToken
from pygments.formatters import HtmlFormatter, LatexFormatter
from pygments.lexer import Lexer # NOQA
from pygments.lexer import Lexer
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.lexers import PythonLexer, Python3Lexer, PythonConsoleLexer, \
CLexer, TextLexer, RstLexer

View File

@@ -9,6 +9,7 @@
"""
import codecs
import warnings
from typing import Any
from docutils.core import Publisher
from docutils.io import FileInput, NullOutput
@@ -16,7 +17,6 @@ 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 typing import Any, Union # NOQA
from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.transforms import (
@@ -39,14 +39,13 @@ from sphinx.versioning import UIDTransform
if False:
# For type annotation
from typing import Any, Dict, List, Tuple, Type, Union # NOQA
from typing import Dict, List, Tuple, Type # NOQA
from docutils import nodes # NOQA
from docutils.frontend import Values # NOQA
from docutils.io import Input # NOQA
from docutils.parsers import Parser # NOQA
from docutils.transforms import Transform # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@@ -23,7 +23,7 @@ from sphinx.util.osutil import mtimes_of_files
if False:
# For type annotation
from typing import Any, Callable, Dict, List, Iterator, Tuple, Union # NOQA
from typing import Dict, List, Union # NOQA
from jinja2.environment import Environment # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.theming import Theme # NOQA

View File

@@ -18,7 +18,7 @@ from sphinx.deprecation import RemovedInSphinx30Warning
if False:
# For type annotation
from typing import Any, Callable, Dict, Iterable, Iterator, List, Tuple, Union # NOQA
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union # NOQA
class _TranslationProxy(UserString):

View File

@@ -18,7 +18,7 @@ from tokenize import COMMENT, NL
if False:
# For type annotation
from typing import Any, Dict, IO, List, Tuple # NOQA
from typing import Any, Dict, List, Tuple # NOQA
comment_re = re.compile('^\\s*#: ?(.*)\r?\n?$')
indent_re = re.compile('^\\s*$')

View File

@@ -25,7 +25,7 @@ from sphinx.util.osutil import abspath
if False:
# For type annotation
from typing import Any, Dict, List, Tuple # NOQA
from typing import Any, Dict # NOQA
class BuildDoc(Command):

View File

@@ -20,12 +20,18 @@ install-info: info
for f in *.info; do \
mkdir -p $(infodir) && \
cp "$$f" $(infodir) && \
$(INSTALL_INFO) --info-dir=$(infodir) "$$f" ; \
$(INSTALL_INFO) --info-dir=$(infodir) "$$f" && \
\
FIGURE_DIR="`basename \"$$f\" .info`-figures" && \
if [ -e "$$FIGURE_DIR" ]; then \
cp -r "$$FIGURE_DIR" $(infodir) ; \
fi; \
done
uninstall-info: info
for f in *.info; do \
rm -f "$(infodir)/$$f" ; \
rm -rf "$(infodir)/`basename '$$f' .info`-figures" && \
$(INSTALL_INFO) --delete --info-dir=$(infodir) "$$f" ; \
done

View File

@@ -25,7 +25,6 @@ from sphinx.util.osutil import relpath
if False:
# For type annotation
from typing import List # NOQA
from typing import Any, Dict, Generator, IO, List, Pattern # NOQA

View File

@@ -27,7 +27,7 @@ logger = logging.getLogger(__name__)
if False:
# For type annotation
from typing import Any, Dict, Iterator, List, Tuple # NOQA
from typing import Any, Dict, List # NOQA
from sphinx.application import Sphinx # NOQA
NODEFAULT = object()

View File

@@ -220,7 +220,9 @@ class CitationReferences(SphinxTransform):
ids=citation_ref["ids"])
refnode.source = citation_ref.source or citation_ref.parent.source
refnode.line = citation_ref.line or citation_ref.parent.line
refnode += nodes.Text('[' + cittext + ']')
refnode += nodes.inline(cittext, '[%s]' % cittext)
for class_name in citation_ref.attributes.get('classes', []):
refnode['classes'].append(class_name)
citation_ref.parent.replace(citation_ref, refnode)
@@ -340,11 +342,7 @@ class SphinxContentsFilter(ContentsFilter):
Used with BuildEnvironment.add_toc_from() to discard cross-file links
within table-of-contents link nodes.
"""
def visit_pending_xref(self, node):
# type: (addnodes.pending_xref) -> None
text = node.astext()
self.parent.append(nodes.literal(text, text))
raise nodes.SkipNode
visit_pending_xref = ContentsFilter.ignore_node_but_process_children
def visit_image(self, node):
# type: (nodes.image) -> None

View File

@@ -20,12 +20,8 @@ from sphinx.util import logging
if False:
# For type annotation
from typing import Any, Callable, Dict, Iterable, List, Tuple # NOQA
from docutils.parsers.rst.states import Inliner # NOQA
from docutils.writers.html4css1 import Writer # NOQA
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.environment import BuildEnvironment # NOQA
logger = logging.getLogger(__name__)

View File

@@ -48,7 +48,7 @@ from sphinx.util.matching import patfilter # noqa
if False:
# For type annotation
from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Pattern, Sequence, Set, Tuple, Type, Union # NOQA
from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Pattern, Set, Tuple, Type, Union # NOQA
logger = logging.getLogger(__name__)

View File

@@ -18,7 +18,6 @@ from sphinx import addnodes
if False:
# For type annotation
from typing import Any, Dict, Type, Union # NOQA
from sphinx.domains import Domain # NOQA
from sphinx.environment import BuildEnvironment # NOQA
from sphinx.util.typing import TextlikeNode # NOQA

View File

@@ -42,7 +42,6 @@ if False:
from sphinx.builders import Builder # NOQA
from sphinx.config import Config # NOQA
from sphinx.environment import BuildEnvironment # NOQA
from sphinx.io import SphinxFileInput # NOQA
from sphinx.util.typing import RoleFunction # NOQA

View File

@@ -27,7 +27,7 @@ except ImportError:
if False:
# For type annotation
from typing import Dict, IO, List, Tuple # NOQA
from typing import IO, Tuple # NOQA
mime_suffixes = OrderedDict([
('.gif', 'image/gif'),

View File

@@ -15,7 +15,7 @@ from sphinx.util import logging
if False:
# For type annotation
from typing import Callable, Dict, IO, Iterator, Tuple # NOQA
from typing import Callable, IO, Iterator # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.environment import BuildEnvironment # NOQA
from sphinx.util.typing import Inventory # NOQA

View File

@@ -22,7 +22,6 @@ from sphinx.util.console import colorize
if False:
# For type annotation
from typing import Any, Dict, Generator, IO, List, Tuple, Type, Union # NOQA
from docutils import nodes # NOQA
from sphinx.application import Sphinx # NOQA

View File

@@ -19,7 +19,7 @@ from sphinx.util import logging
if False:
# For type annotation
from typing import Any, Callable, Iterable, List, Optional, Set, Tuple, Type # NOQA
from typing import Callable, Iterable, List, Optional, Set, Tuple, Type # NOQA
from docutils.parsers.rst.states import Inliner # NOQA
from docutils.statemachine import StringList # NOQA
from sphinx.builders import Builder # NOQA

View File

@@ -24,7 +24,7 @@ from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warnin
if False:
# For type annotation
from typing import Any, Iterator, List, Tuple, Union # NOQA
from typing import Any, Iterator, List, Tuple # NOQA
# Errnos that we need.
EEXIST = getattr(errno, 'EEXIST', 0) # RemovedInSphinx40Warning

View File

@@ -22,7 +22,7 @@ from sphinx.util.typing import NoneType
if False:
# For type annotation
from typing import Any, Callable, Generator # NOQA
from typing import Any, Callable # NOQA
logger = logging.getLogger(__name__)

View File

@@ -1355,8 +1355,9 @@ class TexinfoTranslator(SphinxTranslator):
width = self.tex_image_length(attrs.get('width', ''))
height = self.tex_image_length(attrs.get('height', ''))
alt = self.escape_arg(attrs.get('alt', ''))
filename = "%s-figures/%s" % (self.elements['filename'][:-5], name) # type: ignore
self.body.append('\n@image{%s,%s,%s,%s,%s}\n' %
(name, width, height, alt, ext[1:]))
(filename, width, height, alt, ext[1:]))
def depart_image(self, node):
# type: (nodes.Element) -> None

View File

@@ -12,7 +12,7 @@ from docutils.writers.docutils_xml import Writer as BaseXMLWriter
if False:
# For type annotation
from typing import Any, Tuple # NOQA
from typing import Any # NOQA
from sphinx.builders import Builder # NOQA

View File

@@ -0,0 +1,20 @@
Version markup
--------------
.. versionadded:: 0.6
Some funny **stuff**.
.. versionchanged:: 0.6
Even more funny stuff.
.. deprecated:: 0.6
Boring stuff.
.. versionadded:: 1.2
First paragraph of versionadded.
.. versionchanged:: 1.2
First paragraph of versionchanged.
Second paragraph of versionchanged.

View File

@@ -0,0 +1,24 @@
.. highlightlang:: c
Memory
======
.. c:function:: void* Test_Malloc(size_t n)
Allocate *n* bytes of memory.
.. versionchanged:: 0.6
Can now be replaced with a different allocator.
System
------
Access to the system allocator.
.. versionadded:: 0.6
.. c:function:: void* Test_SysMalloc(size_t n)
Allocate *n* bytes of memory using system allocator.

View File

@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
project = 'Sphinx ChangesBuilder tests'
copyright = '2007-2019 by the Sphinx team, see AUTHORS'
version = '0.6'
release = '0.6alpha1'

View File

@@ -0,0 +1,13 @@
Index for ChangesBuilder tests
==============================
Contents:
.. toctree::
:maxdepth: 2
:caption: Table of Contents
:name: mastertoc
base
c-api
library/utils

View File

@@ -0,0 +1,25 @@
:mod:`utils` --- Fake utilities module for tests
================================================
.. module:: utils
:synopsis: Utility functions
--------------
The :mod:`utils` module is a pretend python module for changes testing.
Classes
-------
.. class:: Path
Class for handling paths.
.. versionadded:: 0.5
Innovative new way to handle paths.
.. deprecated:: 0.6
So, that was a bad idea it turns out.

View File

@@ -10,8 +10,8 @@
import sys
from textwrap import dedent
from unittest import mock
import mock
import pytest
from docutils import nodes
@@ -54,10 +54,10 @@ def nonascii_srcdir(request, rootdir, sphinx_test_tempdir):
# note: this test skips building docs for some builders because they have independent testcase.
# (html, epub, latex, texinfo and manpage)
# (html, changes, epub, latex, texinfo and manpage)
@pytest.mark.parametrize(
"buildername",
['dirhtml', 'singlehtml', 'text', 'changes', 'xml', 'pseudoxml', 'linkcheck'],
['dirhtml', 'singlehtml', 'text', 'xml', 'pseudoxml', 'linkcheck'],
)
@mock.patch('sphinx.builders.linkcheck.requests.head',
side_effect=request_session_head)

View File

@@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
"""
test_build_changes
~~~~~~~~~~~~~~~~~~
Test the ChangesBuilder class.
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import pytest
@pytest.mark.sphinx('changes', testroot='changes')
def test_build(app):
app.build()
# TODO: Use better checking of html content
htmltext = (app.outdir / 'changes.html').text()
assert 'New in version 0.6: Some funny stuff.' in htmltext
assert 'Changed in version 0.6: Even more funny stuff.' in htmltext
assert 'Deprecated since version 0.6: Boring stuff.' in htmltext
path_html = (
'<b>Path</b>: <i>deprecated:</i> Deprecated since version 0.6:'
' So, that was a bad idea it turns out.')
assert path_html in htmltext
malloc_html = (
'<b>Test_Malloc</b>: <i>changed:</i> Changed in version 0.6:'
' Can now be replaced with a different allocator.</a>')
assert malloc_html in htmltext
@pytest.mark.sphinx(
'changes', testroot='changes', srcdir='changes-none',
confoverrides={'version': '0.7', 'release': '0.7b1'})
def test_no_changes(app, status):
app.build()
assert 'no changes in version 0.7.' in status.getvalue()
assert not (app.outdir / 'changes.html').exists()

View File

@@ -391,8 +391,8 @@ def test_html4_output(app, status, warning):
(".//a[@class='footnote-reference brackets'][@href='#id9'][@id='id1']", r"1"),
(".//a[@class='footnote-reference brackets'][@href='#id10'][@id='id2']", r"2"),
(".//a[@class='footnote-reference brackets'][@href='#foo'][@id='id3']", r"3"),
(".//a[@class='reference internal'][@href='#bar'][@id='id4']", r"\[bar\]"),
(".//a[@class='reference internal'][@href='#baz-qux'][@id='id5']", r"\[baz_qux\]"),
(".//a[@class='reference internal'][@href='#bar'][@id='id4']/span", r"\[bar\]"),
(".//a[@class='reference internal'][@href='#baz-qux'][@id='id5']/span", r"\[baz_qux\]"),
(".//a[@class='footnote-reference brackets'][@href='#id11'][@id='id6']", r"4"),
(".//a[@class='footnote-reference brackets'][@href='#id12'][@id='id7']", r"5"),
(".//a[@class='fn-backref'][@href='#id1']", r"1"),

View File

@@ -8,7 +8,9 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import mock
from unittest import mock
import pytest
import sphinx
@@ -257,7 +259,7 @@ def test_conf_warning_message(logger, name, default, annotation, actual, message
config.add(name, default, False, annotation or ())
config.init_values()
check_confval_types(None, config)
logger.warning.assert_called()
assert logger.warning.called
assert logger.warning.call_args[0][0] == message
@@ -276,7 +278,7 @@ def test_check_enum_failed(logger):
config.add('value', 'default', False, ENUM('default', 'one', 'two'))
config.init_values()
check_confval_types(None, config)
logger.warning.assert_called()
assert logger.warning.called
@mock.patch("sphinx.config.logger")
@@ -294,4 +296,4 @@ def test_check_enum_for_list_failed(logger):
config.add('value', 'default', False, ENUM('default', 'one', 'two'))
config.init_values()
check_confval_types(None, config)
logger.warning.assert_called()
assert logger.warning.called

View File

@@ -8,9 +8,10 @@
:license: BSD, see LICENSE for details.
"""
from unittest.mock import Mock
import pytest
from docutils import nodes
from mock import Mock
from sphinx import addnodes
from sphinx.domains.javascript import JavaScriptDomain

View File

@@ -8,9 +8,10 @@
:license: BSD, see LICENSE for details.
"""
from unittest.mock import Mock
import pytest
from docutils import nodes
from mock import Mock
from sphinx import addnodes
from sphinx.domains.python import py_sig_re, _pseudo_parse_arglist, PythonDomain

View File

@@ -8,7 +8,8 @@
:license: BSD, see LICENSE for details.
"""
import mock
from unittest import mock
from docutils import nodes
from sphinx.domains.std import StandardDomain

View File

@@ -9,8 +9,7 @@
"""
from collections import namedtuple
import mock
from unittest import mock
from sphinx import locale
from sphinx.environment.adapters.indexentries import IndexEntries

View File

@@ -10,11 +10,13 @@
import sys
from io import StringIO
from unittest.mock import Mock
import pytest
from sphinx.ext.autosummary import mangle_signature, import_by_name, extract_summary
from sphinx.testing.util import etree_parse
from sphinx.util.docutils import new_document
html_warnfile = StringIO()
@@ -57,8 +59,6 @@ def test_mangle_signature():
def test_extract_summary(capsys):
from sphinx.util.docutils import new_document
from mock import Mock
settings = Mock(language_code='',
id_prefix='',
auto_id_prefix='',

View File

@@ -11,8 +11,8 @@
import os
import unittest
from io import BytesIO
from unittest import mock
import mock
import pytest
import requests
from docutils import nodes

View File

@@ -10,9 +10,7 @@
"""
from collections import namedtuple
from unittest import TestCase
import mock
from unittest import TestCase, mock
from sphinx.application import Sphinx
from sphinx.ext.napoleon import _process_docstring, _skip_member, Config, setup

View File

@@ -12,9 +12,7 @@
from collections import namedtuple
from inspect import cleandoc
from textwrap import dedent
from unittest import TestCase
import mock
from unittest import TestCase, mock
from sphinx.ext.napoleon import Config
from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring

View File

@@ -8,7 +8,8 @@
:license: BSD, see LICENSE for details.
"""
import mock
from unittest import mock
from pygments.formatters.html import HtmlFormatter
from pygments.lexer import RegexLexer
from pygments.token import Text, Name

View File

@@ -8,14 +8,17 @@
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from mock import Mock
from unittest.mock import Mock
from sphinx.roles import emph_literal_role
from docutils import nodes
from sphinx.roles import EmphasizedLiteral
from sphinx.testing.util import assert_node
def test_samp():
emph_literal_role = EmphasizedLiteral()
# normal case
text = 'print 1+{variable}'
ret, msg = emph_literal_role('samp', text, text, 0, Mock())

View File

@@ -10,9 +10,9 @@
import os
import tempfile
from unittest.mock import patch
import pytest
from mock import patch
import sphinx
from sphinx.errors import PycodeError

View File

@@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
import mock
from unittest import mock
from sphinx.jinja2glue import BuiltinTemplateLoader
from sphinx.util.fileutil import copy_asset, copy_asset_file