Skip to content

Commit

Permalink
🔧 Replace flake8 with ruff (#683)
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisjsewell authored Jan 12, 2023
1 parent dff96c4 commit aa3f04d
Show file tree
Hide file tree
Showing 15 changed files with 67 additions and 77 deletions.
17 changes: 7 additions & 10 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,26 @@ repos:
- id: trailing-whitespace

- repo: https://github.com/asottile/pyupgrade
rev: v3.3.0
rev: v3.3.1
hooks:
- id: pyupgrade
args: [--py37-plus]

- repo: https://github.com/PyCQA/isort
rev: 5.10.1
rev: 5.11.4
hooks:
- id: isort

- repo: https://github.com/psf/black
rev: 22.10.0
rev: 22.12.0
hooks:
- id: black

- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.218
hooks:
- id: flake8
additional_dependencies:
- flake8-comprehensions
- flake8-bugbear
# - flake8-self~=0.2.2
- id: ruff
args: ["--force-exclude"]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.991
Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ class StripUnsupportedLatex(SphinxPostTransform):
default_priority = 900

def run(self):
if not self.app.builder.format == "latex":
if self.app.builder.format != "latex":
return
from docutils import nodes

Expand Down
2 changes: 1 addition & 1 deletion myst_parser/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from docutils.nodes import Element

if sys.version_info >= (3, 8):
from typing import Literal, Protocol, TypedDict, get_args, get_origin # noqa: F401
from typing import Literal, Protocol, TypedDict, get_args, get_origin
else:
from typing_extensions import ( # noqa: F401
Literal,
Expand Down
16 changes: 8 additions & 8 deletions myst_parser/_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,11 @@ def field_default(value):
@staticmethod
def field_type(field):
ftypes: Sequence[str]
if get_origin(field.type) is Union:
ftypes = get_args(field.type)
else:
ftypes = [field.type]
ftypes = (
get_args(field.type) if get_origin(field.type) is Union else [field.type]
)
ctype = " | ".join(
str("None" if ftype == type(None) else ftype) # type: ignore # noqa: E721
str("None" if ftype == type(None) else ftype) # type: ignore
for ftype in ftypes
)
ctype = " ".join(ctype.splitlines())
Expand Down Expand Up @@ -87,9 +86,10 @@ def run(self):
if field.metadata.get("extension"):
continue

if self.options.get("scope") == "local":
if field.metadata.get("global_only"):
continue
if self.options.get("scope") == "local" and field.metadata.get(
"global_only"
):
continue

if self.options.get("scope") == "global":
name = f"myst_{name}"
Expand Down
24 changes: 12 additions & 12 deletions myst_parser/mdit_to_docutils/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,10 +342,11 @@ def nested_render_text(
:param inline: whether the text is inline or block
:param allow_headings: whether to allow headings in the text
"""
if inline:
tokens = self.md.parseInline(text, self.md_env)
else:
tokens = self.md.parse(text + "\n", self.md_env)
tokens = (
self.md.parseInline(text, self.md_env)
if inline
else self.md.parse(text + "\n", self.md_env)
)

# remove front matter, if present, e.g. from included documents
if tokens and tokens[0].type == "front_matter":
Expand Down Expand Up @@ -390,10 +391,8 @@ def render_children(self, token: SyntaxTreeNode) -> None:

def add_line_and_source_path(self, node, token: SyntaxTreeNode) -> None:
"""Copy the line number and document source path to the docutils node."""
try:
with suppress(ValueError):
node.line = token_line(token)
except ValueError:
pass
node.source = self.document["source"]

def add_line_and_source_path_r(
Expand Down Expand Up @@ -487,7 +486,7 @@ def update_section_level_state(self, section: nodes.section, level: int) -> None
if section_level <= level
}

def renderInlineAsText(self, tokens: list[SyntaxTreeNode]) -> str:
def renderInlineAsText(self, tokens: list[SyntaxTreeNode]) -> str: # noqa: N802
"""Special kludge for image `alt` attributes to conform CommonMark spec.
Don't try to use it! Spec requires to show `alt` content with stripped markup,
Expand Down Expand Up @@ -1196,9 +1195,10 @@ def render_table_row(self, token: SyntaxTreeNode) -> None:
"text-align:center",
):
entry["classes"].append(f"text-{cast(str, style).split(':')[1]}")
with self.current_node_context(entry, append=True):
with self.current_node_context(para, append=True):
self.render_children(child)
with self.current_node_context(
entry, append=True
), self.current_node_context(para, append=True):
self.render_children(child)

def render_s(self, token: SyntaxTreeNode) -> None:
"""Render a strikethrough token."""
Expand Down Expand Up @@ -1397,7 +1397,7 @@ def render_field_list(self, token: SyntaxTreeNode) -> None:
children = (token.children or [])[:]
while children:
child = children.pop(0)
if not child.type == "fieldlist_name":
if child.type != "fieldlist_name":
error_msg = self.reporter.error(
(
"Expected a fieldlist_name as a child of a field_list"
Expand Down
11 changes: 5 additions & 6 deletions myst_parser/mdit_to_docutils/html_to_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,17 +103,16 @@ def html_to_nodes(

else:
children = child.strip().children
if (
children
title = (
"".join(child.render() for child in children.pop(0))
if children
and children[0].name in ("div", "p")
and (
"title" in children[0].attrs.classes
or "admonition-title" in children[0].attrs.classes
)
):
title = "".join(child.render() for child in children.pop(0))
else:
title = "Note"
else "Note"
)

options = "\n".join(
f":{k}: {v}"
Expand Down
9 changes: 5 additions & 4 deletions myst_parser/mdit_to_docutils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ def is_external_url(
"""
url_check = urlparse(reference)
if known_url_schemes is not None:
scheme_known = url_check.scheme in known_url_schemes
else:
scheme_known = bool(url_check.scheme)
scheme_known = (
url_check.scheme in known_url_schemes
if known_url_schemes is not None
else bool(url_check.scheme)
)
return scheme_known or (match_fragment and url_check.fragment != "")
23 changes: 10 additions & 13 deletions myst_parser/mocking.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,8 @@ def nested_parse(

def parse_target(self, block, block_text, lineno: int):
"""
Taken from https://github.com/docutils-mirror/docutils/blob/e88c5fb08d5cdfa8b4ac1020dd6f7177778d5990/docutils/parsers/rst/states.py#L1927 # noqa: E501
"""
Taken from https://github.com/docutils-mirror/docutils/blob/e88c5fb08d5cdfa8b4ac1020dd6f7177778d5990/docutils/parsers/rst/states.py#L1927
""" # noqa: E501
# Commenting out this code because it only applies to rST
# if block and block[-1].strip()[-1:] == "_": # possible indirect target
# reference = " ".join([line.strip() for line in block])
Expand Down Expand Up @@ -267,16 +267,13 @@ def __getattr__(self, name: str):
been defined. Defined attributes will not be overridden.
"""
cls = type(self).__name__
if hasattr(Body, name):
msg = (
f"{cls} has not yet implemented attribute '{name}'. "
"You can parse RST directly via the `{eval-rst}` directive: "
"https://myst-parser.readthedocs.io/en/latest/syntax/syntax.html#how-directives-parse-content" # noqa: E501
)
else:
# The requested `name` is not a docutils Body element
# (such as "footnote", "block_quote", "paragraph", …)
msg = f"{cls} has no attribute '{name}'"
msg = (
f"{cls} has not yet implemented attribute '{name}'. "
"You can parse RST directly via the `{{eval-rst}}` directive: "
"https://myst-parser.readthedocs.io/en/latest/syntax/syntax.html#how-directives-parse-content"
if hasattr(Body, name)
else f"{cls} has no attribute '{name}'"
)
raise MockingError(msg).with_traceback(sys.exc_info()[2])


Expand Down Expand Up @@ -419,7 +416,7 @@ def run(self) -> list[nodes.Element]:
startline = int(self.options["number-lines"] or 1)
except ValueError:
raise DirectiveError(
3, ":number-lines: with non-integer " "start value"
3, ":number-lines: with non-integer start value"
)
endline = startline + len(file_content.splitlines())
if file_content.endswith("\n"):
Expand Down
9 changes: 5 additions & 4 deletions myst_parser/parsers/parse_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,10 +178,11 @@ def find(
iterator = self.walk() if recurse else self
if include_self:
iterator = itertools.chain([self], iterator)
if inspect.isclass(identifier):
test_func = lambda c: isinstance(c, identifier) # noqa: E731
else:
test_func = lambda c: c.name == identifier # noqa: E731
test_func = (
(lambda c: isinstance(c, identifier))
if inspect.isclass(identifier)
else lambda c: c.name == identifier
)
classes = set(classes) if classes is not None else classes
for child in iterator:
if test_func(child):
Expand Down
2 changes: 1 addition & 1 deletion myst_parser/sphinx_ext/directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def run(self) -> List[nodes.Node]:
finally:
state._renderer.md_config.enable_extensions = myst_extensions

if not len(node.children) == 2:
if len(node.children) != 2:
return [
self.figure_error(
"content should be one image, "
Expand Down
7 changes: 7 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ known_third_party = ["docutils", "markdown_it", "sphinx"]
# Group first party and local folder imports together
no_lines_before = "LOCALFOLDER"

[tool.ruff]
line-length = 100
extend-select = ["B0", "C4", "ICN", "ISC", "N", "RUF", "SIM"]

[tool.mypy]
show_error_codes = true
check_untyped_defs = true
Expand All @@ -113,5 +117,8 @@ warn_unused_ignores = true
module = ["docutils.*", "yaml.*"]
ignore_missing_imports = true

[tool.pytest.ini_options]
filterwarnings = []

[tool.coverage.run]
omit = ["*/_docs.py"]
5 changes: 2 additions & 3 deletions tests/test_anchors.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
def test_print_anchors():
in_stream = StringIO("# a\n\n## b\n\ntext")
out_stream = StringIO()
with mock.patch("sys.stdin", in_stream):
with mock.patch("sys.stdout", out_stream):
print_anchors(["-l", "1"])
with mock.patch("sys.stdin", in_stream), mock.patch("sys.stdout", out_stream):
print_anchors(["-l", "1"])
out_stream.seek(0)
assert out_stream.read().strip() == '<h1 id="a"></h1>'
2 changes: 1 addition & 1 deletion tests/test_docutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
def test_attr_to_optparse_option():
@dataclass
class Config:
name: Literal["a"] = field(default="default")
name: Literal["a"] = field(default="default") # noqa: F821

output = attr_to_optparse_option(fields(Config)[0], "default")
assert len(output) == 3
Expand Down
4 changes: 2 additions & 2 deletions tests/test_renderers/test_include_directive.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def test_render(file_params, tmp_path, monkeypatch):
for node in doctree.traverse():
if node.tagname == "inline" and node["classes"] == ["whitespace"]:
node.parent.remove(node)
output = doctree.pformat().replace(str(tmp_path) + os.sep, "tmpdir" + "/").rstrip()
output = doctree.pformat().replace(str(tmp_path) + os.sep, "tmpdir/").rstrip()

file_params.assert_expected(output, rstrip=True)

Expand All @@ -52,6 +52,6 @@ def test_errors(file_params, tmp_path, monkeypatch):
)

file_params.assert_expected(
report_stream.getvalue().replace(str(tmp_path) + os.sep, "tmpdir" + "/"),
report_stream.getvalue().replace(str(tmp_path) + os.sep, "tmpdir/"),
rstrip=True,
)
11 changes: 0 additions & 11 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,3 @@ commands =
--re-ignore _build/.* \
--port 0 --open-browser \
-n -b {posargs:html} docs/ docs/_build/{posargs:html}


[pytest]
addopts = --ignore=setup.py
markers =
sphinx: set parameters for the sphinx `app` fixture (see ipypublish/sphinx/tests/conftest.py)
filterwarnings =

[flake8]
max-line-length = 100
extend-ignore = E203

0 comments on commit aa3f04d

Please sign in to comment.