Fix linting

pull/185/head
Ashley Whetter 5 years ago
parent a114af76dc
commit a122f00d4a

@ -5,7 +5,7 @@ from .mappers import (
JavaScriptSphinxMapper,
)
default_file_mapping = {
DEFAULT_FILE_PATTERNS = {
"python": ["*.py", "*.pyi"],
"dotnet": ["project.json", "*.csproj", "*.vbproj"],
"go": ["*.go"],
@ -13,13 +13,13 @@ default_file_mapping = {
}
default_ignore_patterns = {
DEFAULT_IGNORE_PATTERNS = {
"dotnet": ["*toc.yml", "*index.yml"],
"python": ["*migrations*"],
}
default_backend_mapping = {
LANGUAGE_MAPPERS = {
"python": PythonSphinxMapper,
"dotnet": DotNetSphinxMapper,
"go": GoSphinxMapper,
@ -29,7 +29,7 @@ default_backend_mapping = {
#: describes backend requirements in form
#: {'backend name': (('1st package name in pypi', '1st package import name'), ...)}
backend_requirements = {
LANGUAGE_REQUIREMENTS = {
"python": (),
"javascript": (),
"go": (("sphinxcontrib-golangdomain", "sphinxcontrib.golangdomain"),),

@ -13,7 +13,7 @@ from sphinx.util.nodes import nested_parse_with_titles
from sphinx.util.rst import escape
class AutoapiSummary(Directive):
class AutoapiSummary(Directive): # pylint: disable=too-few-public-methods
"""A version of autosummary that uses static analysis."""
required_arguments = 0
@ -26,16 +26,6 @@ class AutoapiSummary(Directive):
"template": directives.unchanged,
}
def warn(self, msg):
"""Add a warning message.
:param msg: The warning message to add.
:type msg: str
"""
self.warnings.append(
self.state.document.reporter.warning(msg, line=self.lineno)
)
def _get_names(self):
"""Get the names of the objects to include in the table.
@ -48,8 +38,6 @@ class AutoapiSummary(Directive):
yield line
def run(self):
self.warnings = []
env = self.state.document.settings.env
mapper = env.autoapi_mapper
@ -65,7 +53,7 @@ class AutoapiSummary(Directive):
docname = posixpath.join(tree_prefix, obj.name)
docname = posixpath.normpath(posixpath.join(dirname, docname))
if docname not in env.found_docs:
self.warn("toctree references unknown document {}".format(docname))
self.reporter.warning("toctree references unknown document {}".format(docname))
docnames.append(docname)
tocnode = addnodes.toctree()
@ -77,7 +65,7 @@ class AutoapiSummary(Directive):
tocnode = sphinx.ext.autosummary.autosummary_toc("", "", tocnode)
nodes_.append(tocnode)
return self.warnings + nodes_
return nodes_
def _get_row(self, obj):
template = ":{}:`{} <{}>`\\ {}"
@ -124,7 +112,7 @@ class AutoapiSummary(Directive):
return [table_spec, table]
class NestedParse(Directive):
class NestedParse(Directive): # pylint: disable=too-few-public-methods
"""Nested parsing to remove the first heading of included rST

@ -11,8 +11,8 @@ from .mappers.python import (
PythonAttribute,
PythonException,
)
from . import utils
# pylint: disable=attribute-defined-outside-init,no-self-use,unused-argument
class AutoapiDocumenter(autodoc.Documenter):
def get_attr(self, obj, name, *defargs):
@ -22,7 +22,7 @@ class AutoapiDocumenter(autodoc.Documenter):
attrgetters = self.env.app.registry.autodoc_attrgettrs
else:
# Needed for Sphinx 1.6
attrgetters = autodoc.AutoDirective._special_attrgetters
attrgetters = getattr(autodoc.AutoDirective, "_special_attrgetters")
for type_, func in attrgetters.items():
if isinstance(obj, type_):
@ -82,7 +82,7 @@ class AutoapiDocumenter(autodoc.Documenter):
return False, sorted(children)
class _AutoapiDocstringSignatureMixin(object):
class _AutoapiDocstringSignatureMixin(object): # pylint: disable=too-few-public-methods
def format_signature(self, **kwargs):
# Set "manual" attributes at the last possible moment.
# This is to let a manual entry or docstring searching happen first,
@ -140,7 +140,7 @@ if sphinx.version_info >= (2,):
def format_args(self, **kwargs):
to_format = self.object.args
if re.match("func\W", to_format) or to_format == "func":
if re.match(r"func\W", to_format) or to_format == "func":
if "," not in to_format:
return None

@ -17,12 +17,11 @@ import sphinx.util.logging
from docutils.parsers.rst import directives
from . import documenters
from . import utils
from .backends import (
default_file_mapping,
default_ignore_patterns,
default_backend_mapping,
backend_requirements,
DEFAULT_FILE_PATTERNS,
DEFAULT_IGNORE_PATTERNS,
LANGUAGE_MAPPERS,
LANGUAGE_REQUIREMENTS,
)
from .directives import AutoapiSummary, NestedParse
from .settings import API_ROOT
@ -30,25 +29,25 @@ from .toctree import add_domain_to_toctree
LOGGER = sphinx.util.logging.getLogger(__name__)
default_options = ["members", "undoc-members", "private-members", "special-members"]
_viewcode_cache = {}
_DEFAULT_OPTIONS = ["members", "undoc-members", "private-members", "special-members"]
_VIEWCODE_CACHE = {}
"""Caches a module's parse results for use in viewcode.
:type: dict(str, tuple)
"""
def run_autoapi(app):
def run_autoapi(app): # pylint: disable=too-many-branches
"""
Load AutoAPI data from the filesystem.
"""
if app.config.autoapi_type not in default_backend_mapping:
if app.config.autoapi_type not in LANGUAGE_MAPPERS:
raise ExtensionError(
"Invalid autoapi_type setting, "
"following values is allowed: {}".format(
", ".join(
'"{}"'.format(api_type)
for api_type in sorted(default_backend_mapping)
for api_type in sorted(LANGUAGE_MAPPERS)
)
)
)
@ -81,7 +80,7 @@ def run_autoapi(app):
if not all(
import_name in sys.modules
for _, import_name in backend_requirements[app.config.autoapi_type]
for _, import_name in LANGUAGE_REQUIREMENTS[app.config.autoapi_type]
):
raise ExtensionError(
"AutoAPI of type `{type}` requires following "
@ -92,14 +91,14 @@ def run_autoapi(app):
'{import_name} (available as "{pkg_name}" on PyPI)'.format(
pkg_name=pkg_name, import_name=import_name
)
for pkg_name, import_name in backend_requirements[
for pkg_name, import_name in LANGUAGE_REQUIREMENTS[
app.config.autoapi_type
]
),
)
)
sphinx_mapper = default_backend_mapping[app.config.autoapi_type]
sphinx_mapper = LANGUAGE_MAPPERS[app.config.autoapi_type]
sphinx_mapper_obj = sphinx_mapper(
app, template_dir=app.config.autoapi_template_dir, url_root=url_root
)
@ -108,12 +107,12 @@ def run_autoapi(app):
if app.config.autoapi_file_patterns:
file_patterns = app.config.autoapi_file_patterns
else:
file_patterns = default_file_mapping.get(app.config.autoapi_type, [])
file_patterns = DEFAULT_FILE_PATTERNS.get(app.config.autoapi_type, [])
if app.config.autoapi_ignore:
ignore_patterns = app.config.autoapi_ignore
else:
ignore_patterns = default_ignore_patterns.get(app.config.autoapi_type, [])
ignore_patterns = DEFAULT_IGNORE_PATTERNS.get(app.config.autoapi_type, [])
if ".rst" in app.config.source_suffix:
out_suffix = ".rst"
@ -143,7 +142,7 @@ def build_finished(app, exception):
LOGGER.info(bold("[AutoAPI] ") + darkgreen("Cleaning generated .rst files"))
shutil.rmtree(normalized_root)
sphinx_mapper = default_backend_mapping[app.config.autoapi_type]
sphinx_mapper = LANGUAGE_MAPPERS[app.config.autoapi_type]
if hasattr(sphinx_mapper, "build_finished"):
sphinx_mapper.build_finished(app, exception)
@ -183,7 +182,7 @@ def doctree_read(app, doctree):
LOGGER.info(message_prefix + message)
def clear_env(app, env):
def clear_env(_, env):
"""Clears the environment of the unpicklable objects that we left behind."""
env.autoapi_mapper = None
@ -193,8 +192,8 @@ def viewcode_find(app, modname):
if modname not in mapper.objects:
return None
if modname in _viewcode_cache:
return _viewcode_cache[modname]
if modname in _VIEWCODE_CACHE:
return _VIEWCODE_CACHE[modname]
locations = {}
module = mapper.objects[modname]
@ -225,7 +224,7 @@ def viewcode_find(app, modname):
source = open(module.obj["file_path"]).read()
result = (source, locations)
_viewcode_cache[modname] = result
_VIEWCODE_CACHE[modname] = result
return result
@ -256,7 +255,7 @@ def setup(app):
app.add_config_value("autoapi_type", "python", "html")
app.add_config_value("autoapi_root", API_ROOT, "html")
app.add_config_value("autoapi_ignore", [], "html")
app.add_config_value("autoapi_options", default_options, "html")
app.add_config_value("autoapi_options", _DEFAULT_OPTIONS, "html")
app.add_config_value("autoapi_file_patterns", None, "html")
app.add_config_value("autoapi_dirs", [], "html")
app.add_config_value("autoapi_keep_files", False, "html")

@ -1,10 +1,8 @@
import io
import re
import os
import fnmatch
from collections import OrderedDict, namedtuple
import re
import unidecode
from jinja2 import Environment, FileSystemLoader, TemplateNotFound
import sphinx
import sphinx.util
@ -12,6 +10,7 @@ from sphinx.util.console import darkgreen, bold
from sphinx.util.osutil import ensuredir
from sphinx.util.docstrings import prepare_docstring
import sphinx.util.logging
import unidecode
from ..settings import API_ROOT
@ -33,7 +32,6 @@ class PythonMapperBase(object):
:param obj: JSON object representing this object
:param jinja_env: A template environment for rendering this object
:param url_root: API URL root prefix
Required attributes:
@ -56,15 +54,15 @@ class PythonMapperBase(object):
top_level_object = False
_RENDER_LOG_LEVEL = "VERBOSE"
def __init__(self, obj, app=None, options=None, jinja_env=None, url_root=None):
def __init__(self, obj, jinja_env, app=None, options=None):
self.app = app
self.obj = obj
self.options = options
if jinja_env:
self.jinja_env = jinja_env
if url_root is None:
url_root = os.path.join("/", API_ROOT)
self.url_root = url_root
self.jinja_env = jinja_env
self.url_root = os.path.join("/", API_ROOT)
self.name = None
self.id = None
def render(self, **kwargs):
LOGGER.log(self._RENDER_LOG_LEVEL, "Rendering %s", self.id)
@ -143,7 +141,7 @@ class PythonMapperBase(object):
@property
def display(self):
"""Whether to display this object or not.
:type: bool
"""
return True
@ -156,13 +154,6 @@ class PythonMapperBase(object):
def ref_directive(self):
return self.type
@property
def namespace(self):
pieces = self.id.split(".")[:-1]
if pieces:
return ".".join(pieces)
return None
class SphinxMapperBase(object):
@ -220,13 +211,13 @@ class SphinxMapperBase(object):
if data:
self.paths[path] = data
def find_files(self, patterns, dirs, ignore):
@staticmethod
def find_files(patterns, dirs, ignore):
# pylint: disable=too-many-nested-blocks
if not ignore:
ignore = []
files_to_read = []
for _dir in dirs:
for root, dirnames, filenames in os.walk(_dir):
for root, _, filenames in os.walk(_dir):
for pattern in patterns:
for filename in fnmatch.filter(filenames, pattern):
skip = False
@ -276,7 +267,7 @@ class SphinxMapperBase(object):
def map(self, options=None):
"""Trigger find of serialized sources and build objects"""
for path, data in sphinx.util.status_iterator(
for _, data in sphinx.util.status_iterator(
self.paths.items(),
bold("[AutoAPI] ") + "Mapping Data... ",
length=len(self.paths),
@ -294,7 +285,7 @@ class SphinxMapperBase(object):
raise NotImplementedError
def output_rst(self, root, source_suffix):
for id, obj in sphinx.util.status_iterator(
for _, obj in sphinx.util.status_iterator(
self.objects.items(),
bold("[AutoAPI] ") + "Rendering Data... ",
length=len(self.objects),

@ -105,8 +105,8 @@ class DotNetSphinxMapper(SphinxMapperBase):
_, error_output = proc.communicate()
if error_output:
LOGGER.warning(error_output)
except (OSError, subprocess.CalledProcessError) as e:
LOGGER.warning("Error generating metadata: {0}".format(e))
except (OSError, subprocess.CalledProcessError):
LOGGER.warning("Error generating metadata", exc_info=True)
if raise_error:
raise ExtensionError(
"Failure in docfx while generating AutoAPI output."
@ -137,7 +137,7 @@ class DotNetSphinxMapper(SphinxMapperBase):
# Subclassed to iterate over items
def map(self, options=None):
"""Trigger find of serialized sources and build objects"""
for path, data in sphinx.util.status_iterator(
for _, data in sphinx.util.status_iterator(
self.paths.items(),
bold("[AutoAPI] ") + "Mapping Data... ",
length=len(self.paths),
@ -150,7 +150,7 @@ class DotNetSphinxMapper(SphinxMapperBase):
self.organize_objects()
def create_class(self, data, options=None, path=None, **kwargs):
def create_class(self, data, options=None, **kwargs):
"""
Return instance of class based on Roslyn type property
@ -165,8 +165,8 @@ class DotNetSphinxMapper(SphinxMapperBase):
:param data: dictionary data from Roslyn output artifact
"""
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
kwargs.pop("path", None)
obj_map = {cls.type: cls for cls in ALL_CLASSES}
try:
cls = obj_map[data["type"].lower()]
except KeyError:
@ -176,9 +176,9 @@ class DotNetSphinxMapper(SphinxMapperBase):
data,
jinja_env=self.jinja_env,
options=options,
url_root=self.url_root,
**kwargs
)
obj.url_root = self.url_root
# Append child objects
# TODO this should recurse in the case we're getting back more
@ -228,19 +228,19 @@ class DotNetSphinxMapper(SphinxMapperBase):
_recurse_ns(obj)
# Clean out dead namespaces
for key, ns in self.top_namespaces.copy().items():
if not ns.children:
for key, namespace in self.top_namespaces.copy().items():
if not namespace.children:
del self.top_namespaces[key]
for key, ns in self.namespaces.items():
if not ns.children:
for key, namespace in self.namespaces.copy().items():
if not namespace.children:
del self.namespaces[key]
def output_rst(self, root, source_suffix):
if not self.objects:
raise ExtensionError("No API objects exist. Can't continue")
for id, obj in sphinx.util.status_iterator(
for _, obj in sphinx.util.status_iterator(
self.objects.items(),
bold("[AutoAPI] ") + "Rendering Data... ",
length=len(self.objects),
@ -268,7 +268,7 @@ class DotNetSphinxMapper(SphinxMapperBase):
)
@staticmethod
def build_finished(app, exception):
def build_finished(app, _):
if app.verbosity > 1:
LOGGER.info(bold("[AutoAPI] ") + darkgreen("Cleaning generated .yml files"))
if os.path.exists(DotNetSphinxMapper.DOCFX_OUTPUT_PATH):
@ -343,7 +343,7 @@ class DotNetPythonMapper(PythonMapperBase):
# Inheritance
# TODO Support more than just a class type here, should support enum/etc
self.inheritance = [
DotNetClass({"uid": name, "name": name})
DotNetClass({"uid": name, "name": name}, jinja_env=self.jinja_env)
for name in obj.get("inheritance", [])
]
@ -382,7 +382,7 @@ class DotNetPythonMapper(PythonMapperBase):
repo = self.source["remote"]["repo"].replace(".git", "")
path = self.path
return "{repo}/blob/master/{path}".format(repo=repo, path=path)
except Exception:
except KeyError:
return ""
@property
@ -429,7 +429,7 @@ class DotNetPythonMapper(PythonMapperBase):
See: http://sphinx-doc.org/domains.html#role-cpp:any
"""
return self.name.replace("<", "\<").replace("`", "\`")
return self.name.replace("<", r"\<").replace("`", r"\`")
@property
def ref_short_name(self):
@ -455,7 +455,7 @@ class DotNetPythonMapper(PythonMapperBase):
found = DOC_COMMENT_SEE_PATTERN.search(text)
if found is None:
break
ref = found.group("attr_value").replace("<", "\<").replace("`", "\`")
ref = found.group("attr_value").replace("<", r"\<").replace("`", r"\`")
reftype = "any"
replacement = ""

@ -1,7 +1,7 @@
import json
import subprocess
from sphinx.util.console import darkgreen, bold
from sphinx.util.console import bold
import sphinx.util.logging
from .base import PythonMapperBase, SphinxMapperBase
@ -34,7 +34,7 @@ class GoSphinxMapper(SphinxMapperBase):
"""Read file input into memory, returning deserialized objects
:param path: Path of file to read
:param \**kwargs:
:param **kwargs:
* ignore (``list``): List of file patterns to ignore
"""
# TODO support JSON here

@ -2,7 +2,7 @@ import json
import subprocess
import os
from sphinx.util.console import darkgreen, bold
from sphinx.util.console import bold
import sphinx.util.logging
from .base import PythonMapperBase, SphinxMapperBase
@ -42,7 +42,7 @@ class JavaScriptSphinxMapper(SphinxMapperBase):
# Subclassed to iterate over items
def map(self, options=None):
"""Trigger find of serialized sources and build objects"""
for path, data in sphinx.util.status_iterator(
for _, data in sphinx.util.status_iterator(
self.paths.items(),
bold("[AutoAPI] ") + "Mapping Data... ",
length=len(self.paths),
@ -108,8 +108,6 @@ class JavaScriptPythonMapper(PythonMapperBase):
lambda n: {"name": n["name"], "type": n["type"][0]}, obj.get("param", [])
)
# Language Specific
pass
class JavaScriptClass(JavaScriptPythonMapper):

@ -14,11 +14,11 @@ if sys.version_info < (3,):
_EXCEPTIONS_MODULE = "exceptions"
# getattr to keep linter happy
_STRING_TYPES = getattr(builtins, "basestring")
_zip_longest = itertools.izip_longest
_zip_longest = itertools.izip_longest # pylint: disable=invalid-name,no-member
else:
_EXCEPTIONS_MODULE = "builtins"
_STRING_TYPES = str
_zip_longest = itertools.zip_longest
_STRING_TYPES = (str,)
_zip_longest = itertools.zip_longest # pylint: disable=invalid-name
def resolve_import_alias(name, import_names):
@ -92,11 +92,11 @@ def get_full_basename(node, basename):
import_name = get_full_import_name(assignment, top_level_name)
full_basename = basename.replace(top_level_name, import_name, 1)
break
elif isinstance(assignment, astroid.nodes.Import):
if isinstance(assignment, astroid.nodes.Import):
import_name = resolve_import_alias(top_level_name, assignment.names)
full_basename = basename.replace(top_level_name, import_name, 1)
break
elif isinstance(assignment, astroid.nodes.ClassDef):
if isinstance(assignment, astroid.nodes.ClassDef):
full_basename = "{}.{}".format(assignment.root().name, assignment.name)
break
@ -185,7 +185,7 @@ def get_assign_annotation(node):
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None
:rtype: str or None
"""
annotation = None

@ -3,7 +3,7 @@ import copy
import os
import sphinx.util
from sphinx.util.console import darkgreen, bold
from sphinx.util.console import bold
import sphinx.util.docstrings
import sphinx.util.logging
@ -301,10 +301,10 @@ class PythonSphinxMapper(SphinxMapperBase):
class_content=self.app.config.autoapi_python_class_content,
options=self.app.config.autoapi_options,
jinja_env=self.jinja_env,
url_root=self.url_root,
app=self.app,
**kwargs
)
obj.url_root = self.url_root
lines = sphinx.util.docstrings.prepare_docstring(obj.docstring)
if lines and "autodoc-process-docstring" in self.app.events.events:

@ -1,4 +1,3 @@
import collections
from typing import Optional
import sphinx.util.logging
@ -139,17 +138,9 @@ class PythonPythonMapper(PythonMapperBase):
return skip_undoc_member or skip_private_member or skip_special_member
def _ask_ignore(self, skip): # type: (bool) -> bool
try:
ask_result = self.app.emit_firstresult(
"autoapi-skip-member", self.type, self.id, self, skip, self.options
)
except Exception:
LOGGER.warning(
'Exception occurred while evaluating "autoapi-skip-member" '
'event hook for "{}"'.format(self),
exc_info=True,
)
return skip
ask_result = self.app.emit_firstresult(
"autoapi-skip-member", self.type, self.id, self, skip, self.options
)
return ask_result if ask_result is not None else skip
@ -304,7 +295,7 @@ class PythonClass(PythonPythonMapper):
:type: list(str)
"""
@PythonPythonMapper.args.getter
@property
def args(self):
args = self._args
@ -317,7 +308,11 @@ class PythonClass(PythonPythonMapper):
return args
@PythonPythonMapper.docstring.getter
@args.setter
def args(self, value):
self._args = value
@property
def docstring(self):
docstring = super(PythonClass, self).docstring
@ -332,6 +327,10 @@ class PythonClass(PythonPythonMapper):
return docstring
@docstring.setter
def docstring(self, value):
self._docstring = value
@property
def methods(self):
return self._children_of_type("method")

@ -5,11 +5,6 @@ import sys
import astroid
from . import astroid_utils
try:
_TEXT_TYPE = unicode
except NameError:
_TEXT_TYPE = str
class Parser(object):
def __init__(self):
@ -19,15 +14,15 @@ class Parser(object):
def _get_full_name(self, name):
return ".".join(self._name_stack + [name])
def _encode(self, to_encode):
def _decode(self, to_decode):
if sys.version_info < (3,) and self._encoding:
try:
return _TEXT_TYPE(to_encode, self._encoding)
return unicode(to_decode, self._encoding) # pylint: disable=undefined-variable
except TypeError:
# The string was already in the correct format
pass
return to_encode
return to_decode
def parse_file(self, file_path):
directory, filename = os.path.split(file_path)
@ -69,7 +64,7 @@ class Parser(object):
target = assign_value[0]
value = None
try:
value = self._encode(assign_value[1])
value = self._decode(assign_value[1])
except UnicodeDecodeError:
# Ignore binary data on Python 2.7
if sys.version_info[0] >= 3:
@ -81,7 +76,7 @@ class Parser(object):
"type": type_,
"name": target,
"full_name": self._get_full_name(target),
"doc": self._encode(doc),
"doc": self._decode(doc),
"value": value,
"from_line_no": node.fromlineno,
"to_line_no": node.tolineno,
@ -112,7 +107,7 @@ class Parser(object):
"full_name": self._get_full_name(node.name),
"args": args,
"bases": basenames,
"doc": self._encode(node.doc or ""),
"doc": self._decode(node.doc or ""),
"from_line_no": node.fromlineno,
"to_line_no": node.tolineno,
"children": [],
@ -130,7 +125,7 @@ class Parser(object):
def parse_asyncfunctiondef(self, node):
return self.parse_functiondef(node)
def parse_functiondef(self, node):
def parse_functiondef(self, node): # pylint: disable=too-many-branches
if astroid_utils.is_decorated_with_property_setter(node):
return []
@ -165,7 +160,7 @@ class Parser(object):
"name": node.name,
"full_name": self._get_full_name(node.name),
"args": arg_string,
"doc": self._encode(node.doc or ""),
"doc": self._decode(node.doc or ""),
"from_line_no": node.fromlineno,
"to_line_no": node.tolineno,
"return_annotation": return_annotation,
@ -219,7 +214,7 @@ class Parser(object):
"type": type_,
"name": node.name,
"full_name": node.name,
"doc": self._encode(node.doc or ""),
"doc": self._decode(node.doc or ""),
"children": [],
"file_path": path,
"encoding": node.file_encoding,

@ -70,7 +70,7 @@ def _find_toc_node(toc, ref_id, objtype):
return None
def _get_toc_reference(app, node, toc, docname):
def _get_toc_reference(node, toc, docname):
"""
Logic that understands maps a specific node to it's part of the toctree.
@ -90,8 +90,8 @@ def _get_toc_reference(app, node, toc, docname):
try:
ref_id = node.children[0].attributes["ids"][0]
toc_reference = _find_toc_node(toc, ref_id, addnodes.desc)
except (KeyError, IndexError) as e:
LOGGER.warning("Invalid desc node: %s" % e)
except (KeyError, IndexError):
LOGGER.warning("Invalid desc node", exc_info=True)
toc_reference = None
return toc_reference
@ -119,8 +119,8 @@ def add_domain_to_toctree(app, doctree, docname):
for desc_node in doctree.traverse(addnodes.desc):
try:
ref_id = desc_node.children[0].attributes["ids"][0]
except (KeyError, IndexError) as e:
LOGGER.warning("Invalid desc node: %s" % e)
except (KeyError, IndexError):
LOGGER.warning("Invalid desc node", exc_info=True)
continue
try:
# Python domain object
@ -136,7 +136,7 @@ def add_domain_to_toctree(app, doctree, docname):
)
if parent_node:
toc_reference = _get_toc_reference(app, parent_node, toc, docname)
toc_reference = _get_toc_reference(parent_node, toc, docname)
if toc_reference:
# Get the last child of our parent's bullet list, this is where "we" live.
toc_insertion_point = _traverse_parent(

@ -1,15 +0,0 @@
import unicodedata
import re
# From Django
def slugify(value):
"""
Converts to lowercase, removes non-word characters (alphanumerics and
underscores) and converts spaces to hyphens. Also strips leading and
trailing whitespace.
"""
value = re.sub(r"[^\w\s-]", "", value).strip()
return re.sub(r"[-\s]+", "-", value)

@ -0,0 +1,22 @@
[MASTER]
load-plugins=
[MESSAGES CONTROL]
disable=bad-continuation,
duplicate-code,
fixme,
import-error,
missing-class-docstring,
missing-function-docstring,
missing-module-docstring,
too-many-locals,
too-many-instance-attributes,
useless-object-inheritance
enable=c-extension-no-member
[BASIC]
good-names=i,j,id,_

@ -185,7 +185,7 @@ class DotNetPythonMapperTests(unittest.TestCase):
},
},
}
mapped = dotnet.DotNetPythonMapper(obj)
mapped = dotnet.DotNetPythonMapper(obj, jinja_env=None)
self.assertEqual(
mapped.parameters[0],
{"name": "a", "type": "{TUser}", "desc": "Test :any:`TUser`"},

@ -16,102 +16,102 @@ from autoapi.settings import TEMPLATE_DIR
class DotNetObjectTests(unittest.TestCase):
def test_type(self):
"""Test types of some of the objects"""
obj = dotnet.DotNetNamespace({"id": "Foo.Bar"})
obj = dotnet.DotNetNamespace({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "namespace")
self.assertEqual(obj.ref_type, "namespace")
self.assertEqual(obj.ref_directive, "ns")
obj = dotnet.DotNetMethod({"id": "Foo.Bar"})
obj = dotnet.DotNetMethod({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "method")
self.assertEqual(obj.ref_type, "method")
self.assertEqual(obj.ref_directive, "meth")
obj = dotnet.DotNetProperty({"id": "Foo.Bar"})
obj = dotnet.DotNetProperty({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "property")
self.assertEqual(obj.ref_type, "property")
self.assertEqual(obj.ref_directive, "prop")
obj = dotnet.DotNetEnum({"id": "Foo.Bar"})
obj = dotnet.DotNetEnum({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "enum")
self.assertEqual(obj.ref_type, "enumeration")
self.assertEqual(obj.ref_directive, "enum")
obj = dotnet.DotNetStruct({"id": "Foo.Bar"})
obj = dotnet.DotNetStruct({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "struct")
self.assertEqual(obj.ref_type, "structure")
self.assertEqual(obj.ref_directive, "struct")
obj = dotnet.DotNetConstructor({"id": "Foo.Bar"})
obj = dotnet.DotNetConstructor({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "constructor")
self.assertEqual(obj.ref_type, "constructor")
self.assertEqual(obj.ref_directive, "ctor")
obj = dotnet.DotNetInterface({"id": "Foo.Bar"})
obj = dotnet.DotNetInterface({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "interface")
self.assertEqual(obj.ref_type, "interface")
self.assertEqual(obj.ref_directive, "iface")
obj = dotnet.DotNetDelegate({"id": "Foo.Bar"})
obj = dotnet.DotNetDelegate({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "delegate")
self.assertEqual(obj.ref_type, "delegate")
self.assertEqual(obj.ref_directive, "del")
obj = dotnet.DotNetClass({"id": "Foo.Bar"})
obj = dotnet.DotNetClass({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "class")
self.assertEqual(obj.ref_type, "class")
self.assertEqual(obj.ref_directive, "cls")
obj = dotnet.DotNetField({"id": "Foo.Bar"})
obj = dotnet.DotNetField({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "field")
self.assertEqual(obj.ref_type, "field")
self.assertEqual(obj.ref_directive, "field")
obj = dotnet.DotNetEvent({"id": "Foo.Bar"})
obj = dotnet.DotNetEvent({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.type, "event")
self.assertEqual(obj.ref_type, "event")
self.assertEqual(obj.ref_directive, "event")
def test_names(self):
"""Test names of objects"""
obj = dotnet.DotNetNamespace({"id": "Foo.Bar"})
obj = dotnet.DotNetNamespace({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(obj.name, "Foo.Bar")
self.assertEqual(obj.short_name, "Bar")
obj = dotnet.DotNetNamespace({"id": "Foo.Bar.Something`1"})
obj = dotnet.DotNetNamespace({"id": "Foo.Bar.Something`1"}, jinja_env=None)
self.assertEqual(obj.name, "Foo.Bar.Something`1")
self.assertEqual(obj.short_name, "Something`1")
def test_namespace_namespace(self):
"""Namespace parent resolution"""
ns = dotnet.DotNetNamespace({"id": "Foo.Bar.Widgets"})
ns = dotnet.DotNetNamespace({"id": "Foo.Bar.Widgets"}, jinja_env=None)
self.assertEqual(ns.namespace, "Foo.Bar")
ns = dotnet.DotNetNamespace({"id": "Foo.Bar"})
ns = dotnet.DotNetNamespace({"id": "Foo.Bar"}, jinja_env=None)
self.assertEqual(ns.namespace, "Foo")
ns = dotnet.DotNetNamespace({"id": "Foo"})
ns = dotnet.DotNetNamespace({"id": "Foo"}, jinja_env=None)
self.assertIsNone(ns.namespace)
def test_class_namespace(self):
"""Class parent resolution"""
cls = dotnet.DotNetClass(dict(id="Foo.Bar.Widget", type="class"))
cls = dotnet.DotNetClass(dict(id="Foo.Bar.Widget", type="class"), jinja_env=None)
self.assertEqual(cls.namespace, "Foo.Bar")
cls = dotnet.DotNetClass(dict(id="Foo.Bar", type="class"))
cls = dotnet.DotNetClass(dict(id="Foo.Bar", type="class"), jinja_env=None)
self.assertEqual(cls.namespace, "Foo")
cls = dotnet.DotNetClass(dict(id="Foo", type="class"))
cls = dotnet.DotNetClass(dict(id="Foo", type="class"), jinja_env=None)
self.assertIsNone(cls.namespace)
def test_filename(self):
"""Object file name"""
cls = dotnet.DotNetClass({"id": "Foo.Bar.Widget"})
cls = dotnet.DotNetClass({"id": "Foo.Bar.Widget"}, jinja_env=None)
self.assertEqual(cls.pathname, os.path.join("Foo", "Bar", "Widget"))
cls = dotnet.DotNetClass({"id": "Foo.Bar.Widget<T>"})
cls = dotnet.DotNetClass({"id": "Foo.Bar.Widget<T>"}, jinja_env=None)
self.assertEqual(cls.pathname, os.path.join("Foo", "Bar", "Widget-T"))
cls = dotnet.DotNetClass({"id": "Foo.Bar.Widget<T>(TFoo)"})
cls = dotnet.DotNetClass({"id": "Foo.Bar.Widget<T>(TFoo)"}, jinja_env=None)
self.assertEqual(cls.pathname, os.path.join("Foo", "Bar", "Widget-T"))
cls = dotnet.DotNetClass({"id": "Foo.Foo-Bar.Widget<T>(TFoo)"})
cls = dotnet.DotNetClass({"id": "Foo.Foo-Bar.Widget<T>(TFoo)"}, jinja_env=None)
self.assertEqual(cls.pathname, os.path.join("Foo", "FooBar", "Widget-T"))
cls = dotnet.DotNetClass({"id": u"Foo.Bär"})
cls = dotnet.DotNetClass({"id": u"Foo.Bär"}, jinja_env=None)
self.assertEqual(cls.pathname, os.path.join("Foo", "Bar"))
cls = dotnet.DotNetClass({"id": u"Ащщ.юИфк"})
cls = dotnet.DotNetClass({"id": u"Ащщ.юИфк"}, jinja_env=None)
self.assertEqual(cls.pathname, os.path.join("Ashchshch", "iuIfk"))
def test_rendered_class_escaping(self):
@ -124,7 +124,8 @@ class DotNetObjectTests(unittest.TestCase):
def test_include_path(self):
"""Include path"""
cls = dotnet.DotNetClass({"id": "Foo.Bar.Widget"})
cls = dotnet.DotNetClass({"id": "Foo.Bar.Widget"}, jinja_env=None)
self.assertEqual(cls.include_path, "/autoapi/Foo/Bar/Widget/index")
cls = dotnet.DotNetClass({"id": "Foo.Bar.Widget"}, url_root="/autofoo")
cls = dotnet.DotNetClass({"id": "Foo.Bar.Widget"}, jinja_env=None)
cls.url_root = "/autofoo"
self.assertEqual(cls.include_path, "/autofoo/Foo/Bar/Widget/index")

@ -2,7 +2,7 @@
envlist =
py{27,34,35,36,37}-sphinx{16,17,18},py{35,36,37}-sphinx{20,21}
formatting
#lint (Prospector currently broken)
lint
docs
[travis]
@ -41,12 +41,9 @@ commands =
[testenv:lint]
skip_install = true
deps =
prospector
pylint~=2.4.2
commands =
prospector \
--profile-path={toxinidir} \
--profile=prospector \
--die-on-tool-error {posargs}
pylint {posargs:autoapi}
[testenv:docs]
deps =

Loading…
Cancel
Save