Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements & general refactoring #133

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Enable Ruff linters
AA-Turner committed Jan 30, 2025
commit 7f3c66a59bbb8fa641b00cfa10dc4ecc38691b79
16 changes: 8 additions & 8 deletions .ruff.toml
Original file line number Diff line number Diff line change
@@ -8,21 +8,21 @@ docstring-code-format = true

[lint]
select = [
# "C4", # flake8-comprehensions
# "B", # flake8-bugbear
"C4", # flake8-comprehensions
"B", # flake8-bugbear
"E", # pycodestyle
# "F", # pyflakes
"F", # pyflakes
"FA", # flake8-future-annotations
"FLY", # flynt
"FURB", # refurb
# "G", # flake8-logging-format
"G", # flake8-logging-format
"I", # isort
"LOG", # flake8-logging
"PERF", # perflint
# "PGH", # pygrep-hooks
# "PT", # flake8-pytest-style
# "TC", # flake8-type-checking
# "UP", # pyupgrade
"PGH", # pygrep-hooks
"PT", # flake8-pytest-style
"TC", # flake8-type-checking
"UP", # pyupgrade
"W", # pycodestyle
]
ignore = [
18 changes: 9 additions & 9 deletions docs/script/generate_social_card_previews.py
Original file line number Diff line number Diff line change
@@ -18,17 +18,17 @@
render_social_card,
)

here = Path(__file__).parent
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent

# Dummy lorem text
lorem = """
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
""".split() # noqa
""".split()

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

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

path_tmp = Path(here / "../tmp")
path_tmp = Path(PROJECT_ROOT / "docs/tmp")
path_tmp.mkdir(exist_ok=True)
path_out = Path(path_tmp / f"num_{perm}.png")

@@ -57,7 +57,7 @@
kwargs_fig=kwargs_fig,
)

path_examples_page_folder = here / ".."
path_examples_page_folder = PROJECT_ROOT / "docs"
embed_text.append(
dedent(
f"""
@@ -79,6 +79,6 @@
"""

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

print("Done generating previews of social media cards...")
26 changes: 14 additions & 12 deletions sphinxext/opengraph/__init__.py
Original file line number Diff line number Diff line change
@@ -2,27 +2,29 @@

import os
from pathlib import Path
from typing import Any, Dict
from typing import TYPE_CHECKING
from urllib.parse import urljoin, urlparse, urlsplit, urlunparse

import docutils.nodes as nodes
from sphinx.application import Sphinx

from sphinxext.opengraph.descriptionparser import get_description
from sphinxext.opengraph.metaparser import get_meta_description
from sphinxext.opengraph.titleparser import get_title

if TYPE_CHECKING:
from typing import Any

from sphinx.application import Sphinx

try:
import matplotlib
except ImportError:
print("matplotlib is not installed, social cards will not be generated")
create_social_card = None
DEFAULT_SOCIAL_CONFIG = {}
else:
from sphinxext.opengraph.socialcards import (
DEFAULT_SOCIAL_CONFIG,
create_social_card,
)
except ImportError:
print("matplotlib is not installed, social cards will not be generated")
create_social_card = None
DEFAULT_SOCIAL_CONFIG = {}

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

def get_tags(
app: Sphinx,
context: Dict[str, Any],
context: dict[str, Any],
doctree: nodes.document,
config: Dict[str, Any],
config: dict[str, Any],
) -> str:
# Get field lists for per-page overrides
fields = context["meta"]
@@ -268,14 +270,14 @@ def html_page_context(
app: Sphinx,
pagename: str,
templatename: str,
context: Dict[str, Any],
context: dict[str, Any],
doctree: nodes.document,
) -> None:
if doctree:
context["metatags"] += get_tags(app, context, doctree, app.config)


def setup(app: Sphinx) -> Dict[str, Any]:
def setup(app: Sphinx) -> dict[str, Any]:
# ogp_site_url="" allows relative by default, even though it's not
# officially supported by OGP.
app.add_config_value("ogp_site_url", "", "html")
5 changes: 4 additions & 1 deletion sphinxext/opengraph/descriptionparser.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from __future__ import annotations

import string
from collections.abc import Set
from typing import TYPE_CHECKING

import docutils.nodes as nodes

if TYPE_CHECKING:
from collections.abc import Set


class DescriptionParser(nodes.NodeVisitor):
"""
6 changes: 3 additions & 3 deletions sphinxext/opengraph/socialcards.py
Original file line number Diff line number Diff line change
@@ -57,7 +57,7 @@ def create_social_card(
"""

# 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 # noqa
# 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()
).hexdigest()[:8]
@@ -104,12 +104,12 @@ def create_social_card(

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

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

# These are passed directly from the user configuration to our plotting function
10 changes: 5 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -19,10 +19,10 @@ def rootdir():
return path(__file__).parent.abspath() / "roots"


@pytest.fixture()
@pytest.fixture
def content(app):
app.build(force_all=True)
yield app
return app


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


@pytest.fixture()
@pytest.fixture
def meta_tags(content):
return _meta_tags(content)


@pytest.fixture()
@pytest.fixture
def og_meta_tags(content):
return [
tag for tag in _meta_tags(content) if tag.get("property", "").startswith("og:")
]


@pytest.fixture()
@pytest.fixture
def og_meta_tags_sub(content):
return [
tag
9 changes: 7 additions & 2 deletions tests/test_options.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
from __future__ import annotations

from typing import TYPE_CHECKING

import conftest
import pytest
from sphinx.application import Sphinx
from sphinx.errors import ExtensionError

if TYPE_CHECKING:
from sphinx.application import Sphinx


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

with pytest.raises(Exception):
with pytest.raises(ExtensionError, match="did not provide a valid canonical URL"):
app.build()