Skip to content

Commit

Permalink
馃敡 Move to ruff (#185)
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisjsewell committed May 18, 2024
1 parent 5ad542b commit e1acce2
Show file tree
Hide file tree
Showing 16 changed files with 105 additions and 84 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ jobs:
if: matrix.python-version == '3.8' && matrix.os == 'ubuntu-latest'
uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
name: pytests
flags: pytests
file: ./coverage.xml
Expand Down
23 changes: 7 additions & 16 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,22 @@ exclude: >
repos:

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.6.0
hooks:
- id: check-json
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace

- repo: https://github.com/pycqa/isort
rev: 5.12.0
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.4
hooks:
- id: isort

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

- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
hooks:
- id: flake8
additional_dependencies: [flake8-bugbear~=22.7]
- id: ruff
args: [--fix]
- id: ruff-format

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.10.0
hooks:
- id: mypy
additional_dependencies: []
Expand Down
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Configuration file for the Sphinx documentation builder."""

import os

project = "Sphinx Design"
Expand Down
37 changes: 32 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ testing = [
"pytest~=7.1",
"pytest-cov",
"pytest-regressions",
"defusedxml",
]
theme_furo = ["furo~=2023.7.0"]
theme_pydata = ["pydata-sphinx-theme~=0.13.0"]
Expand All @@ -54,6 +55,37 @@ exclude = [
"tests/",
]

[tool.ruff.lint]
extend-select = [
"B", # flake8-bugbear
"C4", # flake8-comprehensions
# "FURB",# refurb (modernising code)
"I", # isort
"ICN", # flake8-import-conventions
"ISC", # flake8-implicit-str-concat
"N", # pep8-naming
"PERF",# perflint (performance anti-patterns)
"PGH", # pygrep-hooks
"PIE", # flake8-pie
"PL", # pylint
"PTH", # flake8-use-pathlib
"RUF", # Ruff-specific rules
"SIM", # flake8-simplify
"UP", # pyupgrade
"T20", # flake8-print
]
extend-ignore = [
"ISC001", # implicit-str-concat
"PLR2004",
"RUF012",
]

# [tool.ruff.lint.per-file-ignores]
# "..." = ["N801"]

[tool.ruff.lint.isort]
force-sort-within-sections = true

[tool.mypy]
show_error_codes = true
warn_unused_ignores = true
Expand All @@ -64,8 +96,3 @@ strict_equality = true
[[tool.mypy.overrides]]
module = ["docutils.*"]
ignore_missing_imports = true

[tool.isort]
profile = "black"
src_paths = ["sphinx_design", "tests"]
force_sort_within_sections = true
1 change: 1 addition & 0 deletions sphinx_design/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""A sphinx extension for designing beautiful, view size responsive web components."""

from typing import TYPE_CHECKING

__version__ = "0.5.0"
Expand Down
1 change: 1 addition & 0 deletions sphinx_design/_compat.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Helpers for cross compatibility across dependency versions."""

from importlib import resources
from typing import Callable, Iterable

Expand Down
6 changes: 3 additions & 3 deletions sphinx_design/article_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def _parse_text(
output = [para]
return output

def run(self) -> List[nodes.Node]:
def run(self) -> List[nodes.Node]: # noqa: PLR0915
"""Run the directive."""
parse_fields = True # parse field text

Expand All @@ -60,8 +60,8 @@ def run(self) -> List[nodes.Node]:
"sd-p-0",
"sd-mt-2",
"sd-mb-4",
]
+ self.options.get("class-container", []),
*self.options.get("class-container", []),
],
)
self.set_source_info(top_grid)

Expand Down
31 changes: 18 additions & 13 deletions sphinx_design/cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def run(self) -> List[nodes.Node]:
return [self.create_card(self, self.arguments, self.options)]

@classmethod
def create_card(
def create_card( # noqa: PLR0912, PLR0915
cls, inst: SphinxDirective, arguments: Optional[list], options: dict
) -> nodes.Node:
"""Run the directive."""
Expand Down Expand Up @@ -118,7 +118,7 @@ def create_card(
"",
uri=options["img-top"],
alt=img_alt,
classes=["sd-card-img-top"] + options.get("class-img-top", []),
classes=["sd-card-img-top", *options.get("class-img-top", [])],
)
container.append(image_top)

Expand All @@ -137,8 +137,11 @@ def create_card(
if arguments:
title = create_component(
"card-title",
["sd-card-title", "sd-font-weight-bold"]
+ options.get("class-title", []),
[
"sd-card-title",
"sd-font-weight-bold",
*options.get("class-title", []),
],
)
textnodes, _ = inst.state.inline_text(arguments[0], inst.lineno)
title_container = PassthroughTextElement()
Expand All @@ -160,7 +163,7 @@ def create_card(
"",
uri=options["img-bottom"],
alt=img_alt,
classes=["sd-card-img-bottom"] + options.get("class-img-bottom", []),
classes=["sd-card-img-bottom", *options.get("class-img-bottom", [])],
)
container.append(image_bottom)

Expand Down Expand Up @@ -225,7 +228,7 @@ def split_content(content: StringList, offset: int) -> CardContent:
return CardContent(body, header, footer)

@classmethod
def _create_component(
def _create_component( # noqa: PLR0913
cls,
inst: SphinxDirective,
name: str,
Expand All @@ -235,7 +238,7 @@ def _create_component(
) -> nodes.container:
"""Create the header, body, or footer."""
component = create_component(
f"card-{name}", [f"sd-card-{name}"] + options.get(f"class-{name}", [])
f"card-{name}", [f"sd-card-{name}", *options.get(f"class-{name}", [])]
)
inst.set_source_info(component) # TODO set proper lines
inst.state.nested_parse(content, offset, component)
Expand All @@ -246,9 +249,7 @@ def _create_component(
def add_card_child_classes(node):
"""Add classes to specific child nodes."""
for para in findall(node)(nodes.paragraph):
para["classes"] = ([] if "classes" not in para else para["classes"]) + [
"sd-card-text"
]
para["classes"] = [*para.get("classes", []), "sd-card-text"]
# for title in findall(node)(nodes.title):
# title["classes"] = ([] if "classes" not in title else title["classes"]) + [
# "sd-card-title"
Expand All @@ -273,11 +274,15 @@ def run(self) -> List[nodes.Node]:
self.arguments[0].strip()
)
except ValueError as exc:
raise self.error(f"Invalid directive argument: {exc}")
raise self.error(f"Invalid directive argument: {exc}") from exc
container = create_component(
"card-carousel",
["sd-sphinx-override", "sd-cards-carousel", f"sd-card-cols-{cols}"]
+ self.options.get("class", []),
[
"sd-sphinx-override",
"sd-cards-carousel",
f"sd-card-cols-{cols}",
*self.options.get("class", []),
],
)
self.set_source_info(container)
self.state.nested_parse(self.content, self.content_offset, container)
Expand Down
8 changes: 4 additions & 4 deletions sphinx_design/dropdown.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Originally Adapted from sphinxcontrib.details.directive
"""
"""Originally Adapted from sphinxcontrib.details.directive"""

from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.application import Sphinx
Expand All @@ -25,11 +25,11 @@ def setup_dropdown(app: Sphinx) -> None:
app.add_post_transform(DropdownHtmlTransform)


class dropdown_main(nodes.Element, nodes.General):
class dropdown_main(nodes.Element, nodes.General): # noqa: N801
pass


class dropdown_title(nodes.TextElement, nodes.General):
class dropdown_title(nodes.TextElement, nodes.General): # noqa: N801
pass


Expand Down
7 changes: 3 additions & 4 deletions sphinx_design/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,10 @@ def run(self):
classes = directives.class_option(self.arguments[0])
else:
classes = []
except ValueError:
except ValueError as exc:
raise self.error(
'Invalid class attribute value for "%s" directive: "%s".'
% (self.name, self.arguments[0])
)
f'Invalid class attribute value for "{self.name}" directive: "{self.arguments[0]}".'
) from exc
node = create_component("div", rawtext="\n".join(self.content), classes=classes)
if "style" in self.options:
node["style"] = self.options["style"]
Expand Down
16 changes: 8 additions & 8 deletions sphinx_design/grids.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ def _media_option(
continue
try:
int_value = int(value)
except Exception:
raise ValueError(validate_error_msg)
except Exception as exc:
raise ValueError(validate_error_msg) from exc
if not (min_num <= int_value <= max_num):
raise ValueError(validate_error_msg)
return [f"{prefix}{values[0]}"] + [
Expand Down Expand Up @@ -118,7 +118,7 @@ def run(self) -> List[nodes.Node]:
row_columns_option(self.arguments[0]) if self.arguments else []
)
except ValueError as exc:
raise self.error(f"Invalid directive argument: {exc}")
raise self.error(f"Invalid directive argument: {exc}") from exc
self.assert_has_content()
# container-fluid is 100% width for all breakpoints,
# rather than the fixed width of the breakpoint (like container)
Expand Down Expand Up @@ -251,11 +251,11 @@ def run(self) -> List[nodes.Node]:
[
"sd-col",
"sd-d-flex-row",
]
+ self.options.get("columns", [])
+ self.options.get("margin", [])
+ self.options.get("padding", [])
+ self.options.get("class-item", []),
*self.options.get("columns", []),
*self.options.get("margin", []),
*self.options.get("padding", []),
*self.options.get("class-item", []),
],
)
card_options = {
key: value
Expand Down
16 changes: 8 additions & 8 deletions sphinx_design/icons.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ def get_octicon(
"""
try:
data = get_octicon_data()[name]
except KeyError:
raise KeyError(f"Unrecognised octicon: {name}")
except KeyError as exc:
raise KeyError(f"Unrecognised octicon: {name}") from exc

match = HEIGHT_REGEX.match(height)
if not match:
Expand All @@ -85,7 +85,7 @@ def get_octicon(

original_height = 16
if "16" not in data["heights"]:
original_height = int(list(data["heights"].keys())[0])
original_height = int(next(iter(data["heights"].keys())))
elif "24" in data["heights"]:
if height_unit == "px":
if height_value >= 24:
Expand Down Expand Up @@ -172,7 +172,7 @@ def run(self) -> List[nodes.Node]:
return [list_node]


class fontawesome(nodes.Element, nodes.General):
class fontawesome(nodes.Element, nodes.General): # noqa: N801
"""Node for rendering fontawesome icon."""


Expand All @@ -191,7 +191,7 @@ def run(self) -> Tuple[List[nodes.Node], List[nodes.system_message]]:
icon, classes = self.text.split(";", 1) if ";" in self.text else [self.text, ""]
icon = icon.strip()
node = fontawesome(
icon=icon, classes=[self.style, f"fa-{icon}"] + classes.split()
icon=icon, classes=[self.style, f"fa-{icon}", *classes.split()]
)
self.set_source_info(node)
return [node], []
Expand Down Expand Up @@ -257,8 +257,8 @@ def get_material_icon(
"""
try:
data = get_material_icon_data(style)[name]
except KeyError:
raise KeyError(f"Unrecognised material-{style} icon: {name}")
except KeyError as exc:
raise KeyError(f"Unrecognised material-{style} icon: {name}") from exc

match = HEIGHT_REGEX.match(height)
if not match:
Expand All @@ -270,7 +270,7 @@ def get_material_icon(

original_height = 20
if "20" not in data["heights"]:
original_height = int(list(data["heights"].keys())[0])
original_height = int(next(iter(data["heights"].keys())))
elif "24" in data["heights"]:
if height_unit == "px":
if height_value >= 24:
Expand Down

0 comments on commit e1acce2

Please sign in to comment.