Skip to content

Commit cf2aca8

Browse files
committed
Enable Ruff linters
1 parent a8adc0c commit cf2aca8

File tree

7 files changed

+50
-40
lines changed

7 files changed

+50
-40
lines changed

.ruff.toml

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,21 @@ docstring-code-format = true
88

99
[lint]
1010
select = [
11-
# "C4", # flake8-comprehensions
12-
# "B", # flake8-bugbear
11+
"C4", # flake8-comprehensions
12+
"B", # flake8-bugbear
1313
"E", # pycodestyle
14-
# "F", # pyflakes
14+
"F", # pyflakes
1515
"FA", # flake8-future-annotations
1616
"FLY", # flynt
1717
"FURB", # refurb
18-
# "G", # flake8-logging-format
18+
"G", # flake8-logging-format
1919
"I", # isort
2020
"LOG", # flake8-logging
2121
"PERF", # perflint
22-
# "PGH", # pygrep-hooks
23-
# "PT", # flake8-pytest-style
24-
# "TC", # flake8-type-checking
25-
# "UP", # pyupgrade
22+
"PGH", # pygrep-hooks
23+
"PT", # flake8-pytest-style
24+
"TC", # flake8-type-checking
25+
"UP", # pyupgrade
2626
"W", # pycodestyle
2727
]
2828
ignore = [

docs/script/generate_social_card_previews.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,17 @@
1818
render_social_card,
1919
)
2020

21-
here = Path(__file__).parent
21+
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
2222

2323
# Dummy lorem text
2424
lorem = """
2525
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
26-
""".split() # noqa
26+
""".split()
2727

28-
kwargs_fig = dict(
29-
image=here / "../source/_static/og-logo.png",
30-
image_mini=here / "../../sphinxext/opengraph/_static/sphinx-logo-shadow.png",
31-
)
28+
kwargs_fig = {
29+
"image": PROJECT_ROOT / "docs/source/_static/og-logo.png",
30+
"image_mini": PROJECT_ROOT / "sphinxext/opengraph/_static/sphinx-logo-shadow.png",
31+
}
3232

3333
print("Generating previews of social media cards...")
3434
plt_objects = None
@@ -43,7 +43,7 @@
4343
desc = " ".join(lorem[:100])
4444
desc = desc[: MAX_CHAR_DESCRIPTION - 3] + "..."
4545

46-
path_tmp = Path(here / "../tmp")
46+
path_tmp = Path(PROJECT_ROOT / "docs/tmp")
4747
path_tmp.mkdir(exist_ok=True)
4848
path_out = Path(path_tmp / f"num_{perm}.png")
4949

@@ -57,7 +57,7 @@
5757
kwargs_fig=kwargs_fig,
5858
)
5959

60-
path_examples_page_folder = here / ".."
60+
path_examples_page_folder = PROJECT_ROOT / "docs"
6161
embed_text.append(
6262
dedent(
6363
f"""
@@ -79,6 +79,6 @@
7979
"""
8080

8181
# Write markdown text that we can use to embed these images in the docs
82-
(here / "../tmp/embed.txt").write_text(embed_text)
82+
(PROJECT_ROOT / "docs/tmp/embed.txt").write_text(embed_text)
8383

8484
print("Done generating previews of social media cards...")

sphinxext/opengraph/__init__.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,29 @@
22

33
import os
44
from pathlib import Path
5-
from typing import Any, Dict
5+
from typing import TYPE_CHECKING
66
from urllib.parse import urljoin, urlparse, urlsplit, urlunparse
77

88
import docutils.nodes as nodes
9-
from sphinx.application import Sphinx
109

1110
from sphinxext.opengraph.descriptionparser import get_description
1211
from sphinxext.opengraph.metaparser import get_meta_description
1312
from sphinxext.opengraph.titleparser import get_title
1413

14+
if TYPE_CHECKING:
15+
from typing import Any
16+
17+
from sphinx.application import Sphinx
18+
1519
try:
16-
import matplotlib
17-
except ImportError:
18-
print("matplotlib is not installed, social cards will not be generated")
19-
create_social_card = None
20-
DEFAULT_SOCIAL_CONFIG = {}
21-
else:
2220
from sphinxext.opengraph.socialcards import (
2321
DEFAULT_SOCIAL_CONFIG,
2422
create_social_card,
2523
)
24+
except ImportError:
25+
print("matplotlib is not installed, social cards will not be generated")
26+
create_social_card = None
27+
DEFAULT_SOCIAL_CONFIG = {}
2628

2729
__version__ = "0.9.1"
2830
version_info = (0, 9, 1)
@@ -54,9 +56,9 @@ def make_tag(property: str, content: str, type_: str = "property") -> str:
5456

5557
def get_tags(
5658
app: Sphinx,
57-
context: Dict[str, Any],
59+
context: dict[str, Any],
5860
doctree: nodes.document,
59-
config: Dict[str, Any],
61+
config: dict[str, Any],
6062
) -> str:
6163
# Get field lists for per-page overrides
6264
fields = context["meta"]
@@ -268,14 +270,14 @@ def html_page_context(
268270
app: Sphinx,
269271
pagename: str,
270272
templatename: str,
271-
context: Dict[str, Any],
273+
context: dict[str, Any],
272274
doctree: nodes.document,
273275
) -> None:
274276
if doctree:
275277
context["metatags"] += get_tags(app, context, doctree, app.config)
276278

277279

278-
def setup(app: Sphinx) -> Dict[str, Any]:
280+
def setup(app: Sphinx) -> dict[str, Any]:
279281
# ogp_site_url="" allows relative by default, even though it's not
280282
# officially supported by OGP.
281283
app.add_config_value("ogp_site_url", "", "html")

sphinxext/opengraph/descriptionparser.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
from __future__ import annotations
22

33
import string
4-
from collections.abc import Set
4+
from typing import TYPE_CHECKING
55

66
import docutils.nodes as nodes
77

8+
if TYPE_CHECKING:
9+
from collections.abc import Set
10+
811

912
class DescriptionParser(nodes.NodeVisitor):
1013
"""

sphinxext/opengraph/socialcards.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def create_social_card(
5757
"""
5858

5959
# Add a hash to the image path based on metadata to bust caches
60-
# ref: https://developer.twitter.com/en/docs/twitter-for-websites/cards/guides/troubleshooting-cards#refreshing_images # noqa
60+
# ref: https://developer.twitter.com/en/docs/twitter-for-websites/cards/guides/troubleshooting-cards#refreshing_images
6161
hash = hashlib.sha1(
6262
(site_name + page_title + description + str(config_social)).encode()
6363
).hexdigest()[:8]
@@ -104,12 +104,12 @@ def create_social_card(
104104

105105
# If image is an SVG replace it with None
106106
if impath.suffix.lower() == ".svg":
107-
LOGGER.warning(f"[Social card] %s cannot be an SVG image, skipping...", img)
107+
LOGGER.warning("[Social card] %s cannot be an SVG image, skipping...", img)
108108
kwargs_fig[img] = None
109109

110110
# If image doesn't exist, throw a warning and replace with none
111111
if not impath.exists():
112-
LOGGER.warning(f"[Social card]: %s file doesn't exist, skipping...", img)
112+
LOGGER.warning("[Social card]: %s file doesn't exist, skipping...", img)
113113
kwargs_fig[img] = None
114114

115115
# These are passed directly from the user configuration to our plotting function

tests/conftest.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@ def rootdir():
1919
return path(__file__).parent.abspath() / "roots"
2020

2121

22-
@pytest.fixture()
22+
@pytest.fixture
2323
def content(app):
2424
app.build(force_all=True)
25-
yield app
25+
return app
2626

2727

2828
def _meta_tags(content, subdir=None):
@@ -39,19 +39,19 @@ def _og_meta_tags(content):
3939
]
4040

4141

42-
@pytest.fixture()
42+
@pytest.fixture
4343
def meta_tags(content):
4444
return _meta_tags(content)
4545

4646

47-
@pytest.fixture()
47+
@pytest.fixture
4848
def og_meta_tags(content):
4949
return [
5050
tag for tag in _meta_tags(content) if tag.get("property", "").startswith("og:")
5151
]
5252

5353

54-
@pytest.fixture()
54+
@pytest.fixture
5555
def og_meta_tags_sub(content):
5656
return [
5757
tag

tests/test_options.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
from __future__ import annotations
22

3+
from typing import TYPE_CHECKING
4+
35
import conftest
46
import pytest
5-
from sphinx.application import Sphinx
7+
from sphinx.errors import ExtensionError
8+
9+
if TYPE_CHECKING:
10+
from sphinx.application import Sphinx
611

712

813
def get_tag(tags, tag_type, kind="property", prefix="og"):
@@ -315,7 +320,7 @@ def test_rtd_invalid(app: Sphinx, monkeypatch):
315320
monkeypatch.setenv("READTHEDOCS", "True")
316321
app.config.html_baseurl = None
317322

318-
with pytest.raises(Exception):
323+
with pytest.raises(ExtensionError, match="did not provide a valid canonical URL"):
319324
app.build()
320325

321326

0 commit comments

Comments
 (0)