all: Format with black.

Also activate auto formatting. Bump flake8 and mark black
disagreements in setup.cfg.
This commit is contained in:
Laurens Valk
2022-05-27 16:22:05 +02:00
parent 24f7d7c288
commit bd7806d2d4
60 changed files with 716 additions and 709 deletions
+101 -99
View File
@@ -29,15 +29,15 @@ from docutils.parsers.rst import Directive
from sphinx.application import Sphinx
import toml
TOP_DIR = os.path.abspath(os.path.join('..', '..'))
sys.path.insert(0, os.path.join(TOP_DIR, 'src'))
sys.path.append(os.path.abspath('../common/extensions'))
TOP_DIR = os.path.abspath(os.path.join("..", ".."))
sys.path.insert(0, os.path.join(TOP_DIR, "src"))
sys.path.append(os.path.abspath("../common/extensions"))
# ON_RTD is whether we are on readthedocs.org
# this line of code grabbed from docs.readthedocs.org
ON_RTD = os.environ.get('READTHEDOCS', None) == 'True'
ON_RTD = os.environ.get("READTHEDOCS", None) == "True"
_pyproject = toml.load(os.path.join(TOP_DIR, 'pyproject.toml'))
_pyproject = toml.load(os.path.join(TOP_DIR, "pyproject.toml"))
# -- General configuration ------------------------------------------------
@@ -49,29 +49,29 @@ _pyproject = toml.load(os.path.join(TOP_DIR, 'pyproject.toml'))
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.todo',
'sphinx.ext.mathjax',
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx.ext.mathjax",
# Custom Pybricks extensions
'color',
'classlink',
'requirements',
'requirements-static',
'versionchanged',
"color",
"classlink",
"requirements",
"requirements-static",
"versionchanged",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['../common/_templates']
templates_path = ["../common/_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"
# The master toctree document.
master_doc = 'index'
master_doc = "index"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -80,17 +80,17 @@ master_doc = 'index'
# The full version, including alpha/beta/rc tags.
release = "v" + _pyproject["tool"]["poetry"]["version"]
# The short X.Y version.
version = re.match(r'(v\d+\.\d+)', release)[0]
version = re.match(r"(v\d+\.\d+)", release)[0]
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'
language = "en"
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'xcode'
pygments_style = "xcode"
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
@@ -98,10 +98,10 @@ todo_include_todos = True
# Figure numbering
numfig = True
numfig_format = {
'figure': 'Figure %s',
'table': 'Table %s',
'code-block': 'Listing %s',
'section': 'Section %s'
"figure": "Figure %s",
"table": "Table %s",
"code-block": "Listing %s",
"section": "Section %s",
}
# Find cross-reference errors
@@ -109,48 +109,49 @@ nitpicky = True
# https://stackoverflow.com/a/30624034/1976323
nitpick_ignore = [
('py:class', 'bool'),
('py:class', 'bytearray'),
('py:class', 'bytes'),
('py:class', 'callable'),
('py:class', 'dict'),
('py:class', 'float'),
('py:class', 'int'),
('py:class', 'iter'),
('py:class', 'list'),
('py:class', 'object'),
('py:class', 'str'),
('py:class', 'tuple'),
('py:exc', 'OSError'),
('py:exc', 'RuntimeError'),
('py:exc', 'TypeError'),
('py:exc', 'ValueError'),
("py:class", "bool"),
("py:class", "bytearray"),
("py:class", "bytes"),
("py:class", "callable"),
("py:class", "dict"),
("py:class", "float"),
("py:class", "int"),
("py:class", "iter"),
("py:class", "list"),
("py:class", "object"),
("py:class", "str"),
("py:class", "tuple"),
("py:exc", "OSError"),
("py:exc", "RuntimeError"),
("py:exc", "TypeError"),
("py:exc", "ValueError"),
]
# not sure why, but this is needed for typing.IO in uselect
nitpick_ignore.append(('py:obj', 'typing.IO'))
nitpick_ignore.append(("py:obj", "typing.IO"))
# -- Autodoc options ------------------------------------------------------
autodoc_member_order = 'bysource'
autodoc_member_order = "bysource"
autodoc_default_options = {
'members': True,
'undoc-members': True,
"members": True,
"undoc-members": True,
}
autoclass_content = 'both' # This ensures init arguments are not ignored
autoclass_content = "both" # This ensures init arguments are not ignored
add_module_names = False # Hide module name
# -- Options for HTML output ----------------------------------------------
if ON_RTD:
html_theme = 'default'
html_theme = "default"
else:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_context = {
'disclaimer': _DISCLAIMER,
"disclaimer": _DISCLAIMER,
}
# The theme to use for HTML and HTML Help pages. See the documentation for
@@ -163,14 +164,14 @@ html_context = {
# documentation.
#
html_theme_options = {
'style_external_links': True,
'logo_only': True,
"style_external_links": True,
"logo_only": True,
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['../common/_static']
html_static_path = ["../common/_static"]
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
@@ -178,9 +179,9 @@ html_static_path = ['../common/_static']
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
'**': [
'relations.html', # needs 'show_related': True theme option to display
'searchbox.html',
"**": [
"relations.html", # needs 'show_related': True theme option to display
"searchbox.html",
]
}
@@ -190,7 +191,7 @@ html_scaled_image_link = False
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Pybricksdoc'
htmlhelp_basename = "Pybricksdoc"
# -- Options for LaTeX output ---------------------------------------------
@@ -199,14 +200,12 @@ latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
'preamble': r'''
"preamble": r"""
\usepackage{CJKutf8}
\makeatletter
\fancypagestyle{normal}{
@@ -226,51 +225,46 @@ latex_elements = {
\renewcommand{\footrulewidth}{0.4pt}
}
\makeatother
''' % {
'disclaimer': ' '.join((_DISCLAIMER, '©', copyright)),
"""
% {
"disclaimer": " ".join((_DISCLAIMER, "©", copyright)),
},
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
'extraclassoptions': 'openany,oneside',
'releasename': 'Version',
"extraclassoptions": "openany,oneside",
"releasename": "Version",
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, ''.join([project, '-v', version, '.tex']), _TITLE,
author, 'manual'),
(master_doc, "".join([project, "-v", version, ".tex"]), _TITLE, author, "manual"),
]
# -- Content control -----------------------------------------------------
exclude_patterns = [
'ev3devices.rst',
'hubs/ev3brick.rst',
'iodevices/analogsensor.rst',
'iodevices/dcmotor.rst',
'iodevices/ev3devsensor.rst',
'iodevices/i2cdevice.rst',
'iodevices/lumpdevice.rst',
'iodevices/uartdevice.rst',
'media.rst',
'messaging.rst',
'nxtdevices.rst',
'tools/datalog.rst'
"ev3devices.rst",
"hubs/ev3brick.rst",
"iodevices/analogsensor.rst",
"iodevices/dcmotor.rst",
"iodevices/ev3devsensor.rst",
"iodevices/i2cdevice.rst",
"iodevices/lumpdevice.rst",
"iodevices/uartdevice.rst",
"media.rst",
"messaging.rst",
"nxtdevices.rst",
"tools/datalog.rst",
]
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pybricks', 'Pybricks Documentation',
[author], 1)
]
man_pages = [(master_doc, "pybricks", "Pybricks Documentation", [author], 1)]
# -- Options for Texinfo output -------------------------------------------
@@ -279,45 +273,53 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Pybricks', 'Pybricks Documentation',
author, 'Pybricks', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"Pybricks",
"Pybricks Documentation",
author,
"Pybricks",
"One line description of project.",
"Miscellaneous",
),
]
# -- .. availability:: directive
class AvailabilityDirective(Directive):
has_content = True
option_spec = {
'movehub': flag,
'cityhub': flag,
'technichub': flag,
'ev3dev-stretch': flag,
"movehub": flag,
"cityhub": flag,
"technichub": flag,
"ev3dev-stretch": flag,
}
def run(self):
if not self.options:
raise self.error('Must specify at least one platform.')
raise self.error("Must specify at least one platform.")
# TODO: make links to platform pages
return [nodes.emphasis(text='Availability: '),
nodes.Text(', '.join(self.options))]
return [
nodes.emphasis(text="Availability: "),
nodes.Text(", ".join(self.options)),
]
def on_missing_reference(app, env, node, contnode):
# References with special characters can't exist, so we have to supress
# warnings when Sphinx tries to cross reference units like deg/s. For
# consistency, we also treat units without special characters this way.
for unit in ['deg', 'deg/s', 'mm/s', '%', 'mV', 'mA', 'ms']:
for unit in ["deg", "deg/s", "mm/s", "%", "mV", "mA", "ms"]:
# If they match on raw source, we are dealing with argument types.
if unit == contnode.rawsource:
# Return as-is to suppress missing cross reference warning. We
# could make this more fancy by returning an xref node that links
# to the signals page.
return contnode
# Return types are denoted as "int: deg"
try:
# Try to unpack the node.
@@ -325,7 +327,7 @@ def on_missing_reference(app, env, node, contnode):
except ValueError:
# Not a valid format, so skip.
continue
# If it's a match, we could format the node so it looks a bit nicer.
# For now just keep the colon notation as is.
if unit == ret_unit:
@@ -333,8 +335,8 @@ def on_missing_reference(app, env, node, contnode):
def setup(app: Sphinx):
app.add_directive('availability', AvailabilityDirective)
app.connect('missing-reference', on_missing_reference)
app.add_directive("availability", AvailabilityDirective)
app.connect("missing-reference", on_missing_reference)
# -- Python domain hacks ---------------------------------------------------
+13 -11
View File
@@ -13,21 +13,23 @@ class PybricksClasslinkDirective(Directive):
link = name if len(self.arguments) == 1 else self.arguments[1]
html = (
'<a href="{0}.html">'.format(link.lower()) +
'<dl class="py class">' +
'<dt>' +
'<em class="property">class </em>' +
'<code class="sig-name descname">' + name + '</code>' +
'</dt>' +
'<dd></dd>' +
'</dl>' +
'</a>'
'<a href="{0}.html">'.format(link.lower())
+ '<dl class="py class">'
+ "<dt>"
+ '<em class="property">class </em>'
+ '<code class="sig-name descname">'
+ name
+ "</code>"
+ "</dt>"
+ "<dd></dd>"
+ "</dl>"
+ "</a>"
)
# Return the node
node = nodes.raw('', html, format="html")
node = nodes.raw("", html, format="html")
return [node]
def setup(app):
app.add_directive_to_domain('py', 'pybricks-classlink', PybricksClasslinkDirective)
app.add_directive_to_domain("py", "pybricks-classlink", PybricksClasslinkDirective)
+8 -9
View File
@@ -16,28 +16,27 @@ class PybricksColorDirective(Directive):
color = getattr(Color, name)
# Convert HSV to RGB
r, g, b = hsv_to_rgb(color.h/360, color.s/100, color.v/100)
r, g, b = hsv_to_rgb(color.h / 360, color.s / 100, color.v / 100)
# Convert RGB to HEX
rgbhex = '#{0:02x}{1:02x}{2:02x}'.format(
round(r*255),
round(g*255),
round(b*255)
rgbhex = "#{0:02x}{1:02x}{2:02x}".format(
round(r * 255), round(g * 255), round(b * 255)
)
# Render a small block of the given color
css = "background-color: {0}; color: {0}; width: 50px;".format(rgbhex)
if name == "WHITE":
css += "border-style: solid; border-width: 0.5px;" + \
"border-color: #666666;"
css += (
"border-style: solid; border-width: 0.5px;" + "border-color: #666666;"
)
html = '<div id="test" style="{0}">_</div>'.format(css)
# Return the node
node = nodes.raw('', html, format="html")
node = nodes.raw("", html, format="html")
return [node]
def setup(app):
app.add_directive_to_domain('py', 'pybricks-color', PybricksColorDirective)
app.add_directive_to_domain("py", "pybricks-color", PybricksColorDirective)
+26 -25
View File
@@ -10,10 +10,10 @@ FEATURES_SMALL = set()
# Medium feature set.
FEATURES_MEDIUM = FEATURES_SMALL | {
'pybricks-geometry',
'pybricks-iodevices',
'stm32-extra',
'stm32-float',
"pybricks-geometry",
"pybricks-iodevices",
"stm32-extra",
"stm32-float",
}
# Large feature set.
@@ -21,11 +21,11 @@ FEATURES_LARGE = FEATURES_MEDIUM | set()
# Features per hub.
HUB_FEATURES = {
'movehub': {'movehub'} | FEATURES_SMALL,
'cityhub': {'cityhub'} | FEATURES_MEDIUM,
'technichub': {'technichub'} | FEATURES_MEDIUM,
'primehub': {'primehub', 'inventorhub'} | FEATURES_LARGE,
'inventorhub': {'primehub', 'inventorhub'} | FEATURES_LARGE,
"movehub": {"movehub"} | FEATURES_SMALL,
"cityhub": {"cityhub"} | FEATURES_MEDIUM,
"technichub": {"technichub"} | FEATURES_MEDIUM,
"primehub": {"primehub", "inventorhub"} | FEATURES_LARGE,
"inventorhub": {"primehub", "inventorhub"} | FEATURES_LARGE,
}
@@ -40,15 +40,15 @@ class PybricksRequirementsStaticDirective(Directive):
# CC BY-SA 4.0 via https://stackoverflow.com/a/63728208
env = self.state.document.settings.env
destdir = path.join(env.app.builder.outdir, '_images')
destdir = path.join(env.app.builder.outdir, "_images")
if not path.exists(destdir):
makedirs(destdir)
for hub in HUB_FEATURES:
for compat in ("true", "false"):
uri = 'compat_{0}_{1}_label.png'.format(hub, compat)
src_uri = path.join(env.app.builder.srcdir, 'images', uri)
build_uri = path.join(env.app.builder.outdir, '_images', uri)
uri = "compat_{0}_{1}_label.png".format(hub, compat)
src_uri = path.join(env.app.builder.srcdir, "images", uri)
build_uri = path.join(env.app.builder.outdir, "_images", uri)
copyfile(src_uri, build_uri)
# Get requirements from sphinx-directive.
@@ -67,13 +67,14 @@ class PybricksRequirementsStaticDirective(Directive):
depth_path = "../" * depth
# Table row with hub images.
compat_row = "".join([
hub_cell.format(
depth_path,
hub,
"true" if requirements <= features else "false")
for hub, features in HUB_FEATURES.items()
])
compat_row = "".join(
[
hub_cell.format(
depth_path, hub, "true" if requirements <= features else "false"
)
for hub, features in HUB_FEATURES.items()
]
)
# Generate full table.
html = """
@@ -86,16 +87,16 @@ class PybricksRequirementsStaticDirective(Directive):
</tbody>
</table>
</div>
""".format(compat_row)
""".format(
compat_row
)
# Return the node.
node = nodes.raw('', html, format="html")
node = nodes.raw("", html, format="html")
return [node]
def setup(app):
app.add_directive_to_domain(
'py',
'pybricks-requirements-static',
PybricksRequirementsStaticDirective
"py", "pybricks-requirements-static", PybricksRequirementsStaticDirective
)
+14 -14
View File
@@ -29,25 +29,25 @@ from sphinx.util.osutil import copyfile
from sphinx.util import logging
CSS_FILE = 'requirements.css'
JS_FILE = 'requirements.js'
CSS_FILE = "requirements.css"
JS_FILE = "requirements.js"
class PybricksRequirementsDirective(Directive):
has_content = True
option_spec = {'header': directives.unchanged}
option_spec = {"header": directives.unchanged}
required_arguments = 0
optional_arguments = 10
def run(self):
node = nodes.container()
node['classes'].append('toggle-content')
node["classes"].append("toggle-content")
par = nodes.container()
par['classes'].append('toggle-header')
par["classes"].append("toggle-header")
content = '.. pybricks-requirements-static:: ' + " ".join(self.arguments)
content = ".. pybricks-requirements-static:: " + " ".join(self.arguments)
self.state.nested_parse(StringList([content]), self.content_offset, node)
@@ -60,20 +60,20 @@ def add_assets(app):
def copy_assets(app, exception):
if app.builder.name not in ['html', 'readthedocs'] or exception:
if app.builder.name not in ["html", "readthedocs"] or exception:
return
logger = logging.getLogger(__name__)
logger.info('Copying requirements stylesheet/javascript... ', nonl=True)
dest = os.path.join(app.builder.outdir, '_static', CSS_FILE)
logger.info("Copying requirements stylesheet/javascript... ", nonl=True)
dest = os.path.join(app.builder.outdir, "_static", CSS_FILE)
source = os.path.join(os.path.abspath(os.path.dirname(__file__)), CSS_FILE)
copyfile(source, dest)
dest = os.path.join(app.builder.outdir, '_static', JS_FILE)
dest = os.path.join(app.builder.outdir, "_static", JS_FILE)
source = os.path.join(os.path.abspath(os.path.dirname(__file__)), JS_FILE)
copyfile(source, dest)
logger.info('done')
logger.info("done")
def setup(app):
app.add_directive('pybricks-requirements', PybricksRequirementsDirective)
app.connect('builder-inited', add_assets)
app.connect('build-finished', copy_assets)
app.add_directive("pybricks-requirements", PybricksRequirementsDirective)
app.connect("builder-inited", add_assets)
app.connect("build-finished", copy_assets)
+11 -8
View File
@@ -14,15 +14,18 @@ class PybricksVersionDirective(Directive):
def run(self):
html = ""
node = nodes.raw('', html, format="html")
node = nodes.raw("", html, format="html")
return [node]
def setup(app):
if 'ide' in app.tags.tags:
app.add_directive_to_domain('py', 'deprecated',
PybricksVersionDirective, override=True)
app.add_directive_to_domain('py', 'versionadded',
PybricksVersionDirective, override=True)
app.add_directive_to_domain('py', 'versionchanged',
PybricksVersionDirective, override=True)
if "ide" in app.tags.tags:
app.add_directive_to_domain(
"py", "deprecated", PybricksVersionDirective, override=True
)
app.add_directive_to_domain(
"py", "versionadded", PybricksVersionDirective, override=True
)
app.add_directive_to_domain(
"py", "versionchanged", PybricksVersionDirective, override=True
)
+24 -24
View File
@@ -6,48 +6,48 @@
import os
# General information about the project.
project = 'pybricks'
copyright = '2018-2021 The Pybricks Authors'
author = ''
project = "pybricks"
copyright = "2018-2021 The Pybricks Authors"
author = ""
_TITLE = 'Pybricks Modules and Examples'
_DISCLAIMER = 'LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are\
_TITLE = "Pybricks Modules and Examples"
_DISCLAIMER = "LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are\
trademarks and/or copyrights of the LEGO Group of companies \
which does not sponsor, authorize or endorse this site.'
which does not sponsor, authorize or endorse this site."
html_favicon = '../common/images/favicon.ico'
html_logo = '../common/images/pybricks-logo-rtd.png'
latex_logo = '../common/images/pybricks-logo-large.png'
html_favicon = "../common/images/favicon.ico"
html_logo = "../common/images/pybricks-logo-rtd.png"
latex_logo = "../common/images/pybricks-logo-large.png"
# Build main docs for RTD by default.
# Since tags cannot be passed via the TAG make variable on read the docs,
# add it manually.
if os.environ.get('READTHEDOCS', None) == 'True':
tags.add('main') # noqa F821
if os.environ.get("READTHEDOCS", None) == "True":
tags.add("main") # noqa F821
# On https://docs.pybricks.com/en/latest/, show features tagged as beta.
if os.environ.get('READTHEDOCS_VERSION_NAME', None) == 'latest':
tags.add('beta') # noqa F821
if os.environ.get("READTHEDOCS_VERSION_NAME", None) == "latest":
tags.add("beta") # noqa F821
# Addtional configuration of the IDE docs
if 'ide' in tags.tags: # noqa F821
_DISCLAIMER = ''
if "ide" in tags.tags: # noqa F821
_DISCLAIMER = ""
html_show_copyright = False
html_show_sphinx = False
html_css_files = ['css/ide.css']
html_js_files = ['js/ide.js']
html_css_files = ["css/ide.css"]
html_js_files = ["js/ide.js"]
imgmath_image_format = 'svg'
imgmath_image_format = "svg"
imgmath_use_preview = True # requires Sphinx v3
imgmath_latex_preamble = r'''
imgmath_latex_preamble = r"""
\usepackage{newtxsf}
'''
"""
exec(open(os.path.abspath("../common/conf.py")).read())
# Addtional configuration of the IDE docs
if 'ide' in tags.tags: # noqa F821
if "ide" in tags.tags: # noqa F821
extensions.remove('sphinx.ext.mathjax') # noqa F821
extensions.append('sphinx.ext.imgmath') # noqa F821
html_theme_options['prev_next_buttons_location'] = None # noqa F821
extensions.remove("sphinx.ext.mathjax") # noqa F821
extensions.append("sphinx.ext.imgmath") # noqa F821
html_theme_options["prev_next_buttons_location"] = None # noqa F821