Skip to content

Commit

Permalink
Enable more linter categories in Ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
AA-Turner committed Jan 31, 2025
1 parent a5e22d3 commit 3597d31
Show file tree
Hide file tree
Showing 11 changed files with 89 additions and 53 deletions.
55 changes: 54 additions & 1 deletion .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,75 @@ docstring-code-format = true

[lint]
select = [
"C4", # flake8-comprehensions
"ANN", # flake8-annotations
"ASYNC", # flake8-async
"B", # flake8-bugbear
"BLE", # flake8-blind-except
"C4", # flake8-comprehensions
"D", # pydocstyle
"D212", # Multi-line docstring summary should start at the first line
"D417", # Missing argument description in the docstring for `{definition}`: `{name}`
"DTZ", # flake8-datetimez
"E", # pycodestyle
"EM", # flake8-errmsg
"EXE", # flake8-executable
"F", # pyflakes
"FA", # flake8-future-annotations
"FIX", # flake8-fixme
"FLY", # flynt
"FURB", # refurb
"G", # flake8-logging-format
"I", # isort
"ICN", # flake8-import-conventions
"INT", # flake8-gettext
"ISC", # flake8-implicit-str-concat
"LOG", # flake8-logging
"N", # pep8-naming
"PERF", # perflint
"PGH", # pygrep-hooks
"PIE", # flake8-pie
"PLC", # pylint
"PLE", # pylint
"PLW", # pylint
"PT", # flake8-pytest-style
"PTH", # flake8-use-pathlib
"Q", # flake8-quotes
"RET", # flake8-return
"RSE", # flake8-raise
"RUF", # Ruff-specific rules
"S", # flake8-bandit
"SIM", # flake8-simplify
"SLF", # flake8-self
"SLOT", # flake8-slots
"T10", # flake8-debugger
"TC", # flake8-type-checking
"TD", # flake8-todos
"TID", # flake8-tidy-imports
"TRY", # tryceratops
"UP", # pyupgrade
"W", # pycodestyle
"W", # pycodestyle
"YTT", # flake8-2020
]
ignore = [
# pydocstyle
"D100", # Missing docstring in public module
"D102", # Missing docstring in public method
"D103", # Missing docstring in public function
"D104", # Missing docstring in public package
"D107", # Missing docstring in `__init__`
"D400", # First line should end with a period
# pycodestyle
"E501", # Ignore line length errors (we use auto-formatting)
]

[lint.per-file-ignores]
"tests/*" = [
"ANN", # tests don't need annotations
"S101", # allow use of assert
"SLF001", # allow private member access
]

[lint.flake8-type-checking]
exempt-modules = []
strict = true
Expand All @@ -40,3 +88,8 @@ forced-separate = [
required-imports = [
"from __future__ import annotations",
]

[lint.pydocstyle]
convention = "pep257"
ignore-decorators = ["typing.overload"]
ignore-var-parameters = true
4 changes: 2 additions & 2 deletions docs/script/generate_social_card_previews.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
A helper script to test out what social previews look like.
"""A helper script to test out what social previews look like.
I should remove this when I'm happy with the result.
"""

Expand Down
16 changes: 5 additions & 11 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,15 @@
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#

from __future__ import annotations

import os
import sys
from pathlib import Path
from subprocess import run

sys.path.insert(0, os.path.abspath("../.."))
# -- Path setup --------------------------------------------------------------

sys.path.insert(0, str(Path(__file__).parent.parent.parent))

# -- Project information -----------------------------------------------------

Expand Down Expand Up @@ -72,5 +66,5 @@
}

# Generate sample social media preview images
path_script = os.path.abspath("../script/generate_social_card_previews.py")
run(f"python {path_script}", shell=True)
path_script = Path(__file__, "..", "..", "script", "generate_social_card_previews.py").resolve()
run(("python", path_script), check=False) # NoQA: S603
12 changes: 6 additions & 6 deletions noxfile.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
Configuration to automatically run jobs and tests via `nox`.
"""Configuration to automatically run jobs and tests via `nox`.
For example, to build the documentation with a live server:
nox -s docs -- live
Expand All @@ -21,7 +21,7 @@


@nox.session
def docs(session):
def docs(session: nox.Session) -> None:
"""Build the documentation. Use `-- live` to build with a live server."""
session.install("-r", "docs/requirements.txt")
session.install("-e", ".")
Expand All @@ -31,13 +31,13 @@ def docs(session):
session.run(*split("sphinx-autobuild -b html docs/source docs/build/html"))
else:
session.run(
*split("sphinx-build -nW --keep-going -b html docs/source docs/build/html")
*split("sphinx-build -nW --keep-going -b html docs/source docs/build/html"),
)


@nox.session
def test(session):
def test(session: nox.Session) -> None:
"""Run the test suite."""
session.install("-e", ".")
session.install("-r", "dev-requirements.txt")
session.run(*(["pytest"] + session.posargs))
session.run("pytest", *session.posargs)
9 changes: 4 additions & 5 deletions sphinxext/opengraph/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from typing import TYPE_CHECKING
from urllib.parse import urljoin, urlparse, urlsplit, urlunsplit

import docutils.nodes as nodes
from docutils import nodes

from sphinxext.opengraph.descriptionparser import get_description
from sphinxext.opengraph.metaparser import get_meta_description
Expand Down Expand Up @@ -197,7 +197,7 @@ def get_tags(
image_url_parsed = urlparse(image_url)
if not image_url_parsed.scheme:
# Relative image path detected, relative to the source. Make absolute.
if first_image:
if first_image: # NoQA: SIM108
root = page_url
else: # ogp_image is set
# ogp_image is defined as being relative to the site root.
Expand Down Expand Up @@ -256,7 +256,7 @@ def social_card_for_page(
outdir: str | Path,
config: Config,
env: BuildEnvironment,
):
) -> str:
# Description
description_max_length = config_social.get(
"description_max_length", DEFAULT_DESCRIPTION_LENGTH_SOCIAL_CARDS - 3
Expand Down Expand Up @@ -294,8 +294,7 @@ def social_card_for_page(
# We use os.path.sep to standardize behavior acros *nix and Windows
url = config.ogp_site_url.strip("/")
image_path = str(image_path).replace(os.path.sep, "/").strip("/")
image_url = f"{url}/{image_path}"
return image_url
return f"{url}/{image_path}"


def html_page_context(
Expand Down
6 changes: 2 additions & 4 deletions sphinxext/opengraph/descriptionparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,14 @@
import string
from typing import TYPE_CHECKING

import docutils.nodes as nodes
from docutils import nodes

if TYPE_CHECKING:
from collections.abc import Set


class DescriptionParser(nodes.NodeVisitor):
"""
Finds the title and creates a description from a doctree
"""
"""Finds the title and creates a description from a doctree."""

def __init__(
self,
Expand Down
4 changes: 1 addition & 3 deletions sphinxext/opengraph/metaparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@


class HTMLTextParser(HTMLParser):
"""
Parse HTML into text
"""
"""Parse HTML into text."""

def __init__(self) -> None:
super().__init__()
Expand Down
19 changes: 8 additions & 11 deletions sphinxext/opengraph/socialcards.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from pathlib import Path
from typing import TYPE_CHECKING

import matplotlib
import matplotlib as mpl
import matplotlib.font_manager
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
Expand All @@ -22,7 +22,7 @@

PltObjects: TypeAlias = tuple[Figure, Text, Text, Text, Text]

matplotlib.use("agg")
mpl.use("agg")

LOGGER = logging.getLogger(__name__)
HERE = Path(__file__).parent
Expand Down Expand Up @@ -77,11 +77,11 @@ def create_social_card(
It also passes configuration through to the rendering function.
If Matplotlib objects are present in the `app` environment, it reuses them.
"""

# Add a hash to the image path based on metadata to bust caches
# ref: https://developer.twitter.com/en/docs/twitter-for-websites/cards/guides/troubleshooting-cards#refreshing_images
hash = hashlib.sha1(
(site_name + page_title + description + str(config_social)).encode()
(site_name + page_title + description + str(config_social)).encode(),
usedforsecurity=False,
).hexdigest()[:8]

# Define the file path we'll use for this image
Expand Down Expand Up @@ -156,8 +156,7 @@ def create_social_card(
env.ogp_social_card_plt_objects = plt_objects

# Path relative to build folder will be what we use for linking the URL
path_relative_to_build = path_images_relative / filename_image
return path_relative_to_build
return path_images_relative / filename_image


def render_social_card(
Expand Down Expand Up @@ -236,9 +235,7 @@ def create_social_card_objects(
left_margin,
site_title_y_offset,
"Test site title",
{
"size": 24,
},
{"size": 24},
ha="left",
va="top",
wrap=True,
Expand All @@ -260,7 +257,7 @@ def create_social_card_objects(
c=page_title_color,
)

txt_page._get_wrap_line_width = _set_page_title_line_width
txt_page._get_wrap_line_width = _set_page_title_line_width # NoQA: SLF001

# description
# Just below site title, smallest font and many lines.
Expand All @@ -280,7 +277,7 @@ def create_social_card_objects(
wrap=True,
c=description_color,
)
txt_description._get_wrap_line_width = _set_description_line_width
txt_description._get_wrap_line_width = _set_description_line_width # NoQA: SLF001

# url
# Aligned to the left of the mini image
Expand Down
4 changes: 1 addition & 3 deletions sphinxext/opengraph/titleparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@


class HTMLTextParser(HTMLParser):
"""
Parse HTML into text
"""
"""Parse HTML into text."""

def __init__(self) -> None:
super().__init__()
Expand Down
6 changes: 3 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@

@pytest.fixture(scope="session")
def rootdir():
if sphinx.version_info[:2] >= (7, 0):
return Path(__file__).parent.resolve() / "roots"
else:
if sphinx.version_info[:2] < (7, 2):
from sphinx.testing.path import path

return path(__file__).parent.abspath() / "roots"

return Path(__file__).parent.resolve() / "roots"


@pytest.fixture
def content(app):
Expand Down
7 changes: 3 additions & 4 deletions tests/test_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@


def get_tag(tags, tag_type, kind="property", prefix="og"):
return [tag for tag in tags if tag.get(kind) == f"{prefix}:{tag_type}"][0]
return next(tag for tag in tags if tag.get(kind) == f"{prefix}:{tag_type}")


def get_tag_content(tags, tag_type, kind="property", prefix="og"):
Expand All @@ -20,9 +20,8 @@ def get_tag_content(tags, tag_type, kind="property", prefix="og"):


def get_meta_description(tags):
return [tag for tag in tags if tag.get("name") == "description"][0].get(
"content", ""
)
tag = next(tag for tag in tags if tag.get("name") == "description")
return tag.get("content", "")


@pytest.mark.sphinx("html", testroot="simple")
Expand Down

0 comments on commit 3597d31

Please sign in to comment.