Skip to content

Commit

Permalink
Linting: Aggressive ruff pass (ruff v0.3.4, #419)
Browse files Browse the repository at this point in the history
  • Loading branch information
tony committed Mar 24, 2024
2 parents b98b873 + f7bb908 commit bec4723
Show file tree
Hide file tree
Showing 23 changed files with 72 additions and 63 deletions.
19 changes: 19 additions & 0 deletions CHANGES
Expand Up @@ -10,6 +10,25 @@

- Re-implement support Python 3.8 (#417)

### Development

- Aggressive automated lint fixes via `ruff` (#419)

via ruff v0.3.4, all automated lint fixes, including unsafe and previews were applied:

```sh
ruff check --select ALL . --fix --unsafe-fixes --preview --show-fixes; ruff format .
```

Branches were treated with:

```sh
git rebase \
--strategy-option=theirs \
--exec 'poetry run ruff check --select ALL . --fix --unsafe-fixes --preview --show-fixes; poetry run ruff format .; git add src tests; git commit --amend --no-edit' \
origin/master
```

## django-docutils 0.23.0 (2024-02-06)

_Maintenance release only, no bug fixes or new features_
Expand Down
17 changes: 8 additions & 9 deletions docs/conf.py
Expand Up @@ -206,15 +206,14 @@ def linkcode_resolve(domain: str, info: t.Dict[str, str]) -> t.Union[None, str]:
fn,
linespec,
)
else:
return "{}/blob/v{}/{}/{}/{}{}".format(
about["__github__"],
about["__version__"],
"src",
about["__package_name__"],
fn,
linespec,
)
return "{}/blob/v{}/{}/{}/{}{}".format(
about["__github__"],
about["__version__"],
"src",
about["__package_name__"],
fn,
linespec,
)


def remove_tabs_js(app: "Sphinx", exc: Exception) -> None:
Expand Down
3 changes: 2 additions & 1 deletion src/django_docutils/_internal/types.py
Expand Up @@ -7,10 +7,11 @@
.. _typeshed's: https://github.com/python/typeshed/blob/5df8de7/stdlib/_typeshed/__init__.pyi#L115-L118
""" # E501

from os import PathLike
from typing import TYPE_CHECKING, Union

if TYPE_CHECKING:
from os import PathLike

from typing_extensions import TypeAlias

StrPath: "TypeAlias" = Union[str, "PathLike[str]"] # stable
Expand Down
2 changes: 0 additions & 2 deletions src/django_docutils/exc.py
Expand Up @@ -4,8 +4,6 @@
class DjangoDocutilsException(Exception):
"""Base exception for Django Docutils package."""

pass


class DocutilsNotInstalled(DjangoDocutilsException):
"""Docutils is not installed."""
Expand Down
8 changes: 4 additions & 4 deletions src/django_docutils/lib/directives/code.py
Expand Up @@ -75,9 +75,9 @@ def patch_bash_session_lexer() -> None:
# 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
}

DEFAULT_OPTION_SPEC: t.Dict[str, t.Callable[[str], t.Any]] = {
key: directives.flag for key in VARIANTS
}
DEFAULT_OPTION_SPEC: t.Dict[str, t.Callable[[str], t.Any]] = dict.fromkeys(
VARIANTS, directives.flag
)


class CodeBlock(Directive):
Expand All @@ -100,7 +100,7 @@ def run(self) -> t.List[nodes.Node]:
# no lexer found - use the text one instead of an exception
lexer = TextLexer()
# take an arbitrary option if more than one is given
formatter = self.options and VARIANTS[next(iter(self.options))] or DEFAULT
formatter = (self.options and VARIANTS[next(iter(self.options))]) or DEFAULT
parsed = highlight("\n".join(self.content), lexer, formatter)
return [nodes.raw("", parsed, format="html")]

Expand Down
2 changes: 1 addition & 1 deletion src/django_docutils/lib/directives/registry.py
Expand Up @@ -3,7 +3,7 @@
from django.utils.module_loading import import_string
from docutils.parsers.rst import directives

from ..settings import DJANGO_DOCUTILS_LIB_RST
from django_docutils.lib.settings import DJANGO_DOCUTILS_LIB_RST


def register_django_docutils_directives() -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/django_docutils/lib/metadata/process.py
Expand Up @@ -34,7 +34,7 @@ def process_datetime(metadata):

from django.utils.module_loading import import_string

from ..settings import DJANGO_DOCUTILS_LIB_RST
from django_docutils.lib.settings import DJANGO_DOCUTILS_LIB_RST


def process_metadata(metadata: t.Dict[str, str]) -> t.Dict[str, str]:
Expand Down
4 changes: 2 additions & 2 deletions src/django_docutils/lib/metadata/tests/test_extract.py
Expand Up @@ -5,12 +5,12 @@
from django.utils.encoding import force_bytes
from docutils.core import publish_doctree

from ...settings import DJANGO_DOCUTILS_LIB_RST
from ..extract import (
from django_docutils.lib.metadata.extract import (
extract_metadata,
extract_subtitle,
extract_title,
)
from django_docutils.lib.settings import DJANGO_DOCUTILS_LIB_RST


def test_extract_title() -> None:
Expand Down
4 changes: 2 additions & 2 deletions src/django_docutils/lib/metadata/tests/test_process.py
Expand Up @@ -5,8 +5,8 @@
from django.utils.encoding import force_bytes
from docutils.core import publish_doctree

from ..extract import extract_metadata
from ..process import process_metadata
from django_docutils.lib.metadata.extract import extract_metadata
from django_docutils.lib.metadata.process import process_metadata


def test_process_metadata_file() -> None:
Expand Down
3 changes: 1 addition & 2 deletions src/django_docutils/lib/publisher.py
Expand Up @@ -182,5 +182,4 @@ def publish_html_from_doctree(

if show_title:
return mark_safe(force_str(parts["html_body"]))
else:
return mark_safe(force_str(parts["fragment"]))
return mark_safe(force_str(parts["fragment"]))
19 changes: 9 additions & 10 deletions src/django_docutils/lib/roles/common.py
Expand Up @@ -4,7 +4,7 @@

from docutils import nodes, utils

from ..utils import split_explicit_title
from django_docutils.lib.utils import split_explicit_title

if t.TYPE_CHECKING:
from .types import RemoteUrlHandlerFn, RoleFnReturnValue, UrlHandlerFn
Expand Down Expand Up @@ -58,15 +58,14 @@ def url_handler(target):

if not has_explicit_title:
title = utils.unescape(title)
else:
if title[:2] == "**" and title[-2:] == "**":
innernodeclass = nodes.strong
title = title.strip("**") # noqa: B005
# In Python 3.9+
# title = title.removeprefix("**").removesuffix("**")
elif title[0] == "*" and title[-1] == "*":
innernodeclass = nodes.emphasis
title = title.strip("*")
elif title[:2] == "**" and title[-2:] == "**":
innernodeclass = nodes.strong
title = title.strip("**") # noqa: B005
# In Python 3.9+
# title = title.removeprefix("**").removesuffix("**")
elif title[0] == "*" and title[-1] == "*":
innernodeclass = nodes.emphasis
title = title.strip("*")

url = url_handler_fn(target)

Expand Down
8 changes: 4 additions & 4 deletions src/django_docutils/lib/roles/registry.py
Expand Up @@ -6,7 +6,7 @@
from django.utils.module_loading import import_string
from docutils.parsers.rst import roles

from ..settings import DJANGO_DOCUTILS_LIB_RST
from django_docutils.lib.settings import DJANGO_DOCUTILS_LIB_RST


def register_django_docutils_roles() -> None:
Expand Down Expand Up @@ -62,10 +62,10 @@ def register_django_docutils_roles() -> None:
None
"""
if not DJANGO_DOCUTILS_LIB_RST:
return None
return

if "roles" not in DJANGO_DOCUTILS_LIB_RST:
return None
return

django_docutils_roles = DJANGO_DOCUTILS_LIB_RST["roles"]

Expand All @@ -74,7 +74,7 @@ def register_django_docutils_roles() -> None:
if local_roles:
register_role_mapping(local_roles)

return None
return


def register_role_mapping(role_mapping: t.Dict[str, t.Any]) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/django_docutils/lib/roles/types.py
Expand Up @@ -32,7 +32,7 @@ def __call__(self, target: str) -> t.Tuple[str, str]:
<https://docutils.sourceforge.io/docs/howto/rst-roles.html>`_:
Role functions return a tuple of two values:
- A list of nodes which will be inserted into the document tree at the point where
the interpreted role was encountered (can be an empty list).
- A list of system messages, which will be inserted into the document tree
Expand Down
2 changes: 1 addition & 1 deletion src/django_docutils/lib/tests/test_utils.py
@@ -1,6 +1,6 @@
"""Tests for Django Docutil utilities."""

from ..utils import chop_after_docinfo, chop_after_title
from django_docutils.lib.utils import chop_after_docinfo, chop_after_title


def test_chop_after_title() -> None:
Expand Down
6 changes: 3 additions & 3 deletions src/django_docutils/lib/tests/test_writers.py
Expand Up @@ -4,9 +4,9 @@
from docutils.core import publish_doctree
from docutils.writers.html5_polyglot import Writer

from ..publisher import publish_parts_from_doctree
from ..settings import DJANGO_DOCUTILS_LIB_RST
from ..writers import DjangoDocutilsWriter
from django_docutils.lib.publisher import publish_parts_from_doctree
from django_docutils.lib.settings import DJANGO_DOCUTILS_LIB_RST
from django_docutils.lib.writers import DjangoDocutilsWriter


def test_HTMLWriter_hides_docinfo() -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/django_docutils/lib/transforms/code.py
Expand Up @@ -112,7 +112,7 @@ def apply(self, **kwargs: t.Any) -> None:
patch_bash_session_lexer()

newlexer = BashSessionLexer()
elif text.startswith("{%") or text.startswith("{{"):
elif text.startswith(("{%", "{{")):
from pygments.lexers.templates import DjangoLexer

newlexer = DjangoLexer()
Expand Down
5 changes: 2 additions & 3 deletions src/django_docutils/lib/transforms/toc.py
Expand Up @@ -54,7 +54,7 @@ def build_contents(
ref_id = self.document.set_id(reference)
item = nodes.list_item("", reference)
if (
self.backlinks in ("entry", "top")
self.backlinks in {"entry", "top"}
and title.next_node(nodes.reference) is None
and isinstance(title, (nodes.Element, nodes.TextElement))
):
Expand All @@ -72,5 +72,4 @@ def build_contents(
if auto:
contents["classes"].append("auto-toc")
return contents
else:
return []
return []
2 changes: 0 additions & 2 deletions src/django_docutils/lib/utils.py
Expand Up @@ -125,5 +125,3 @@ def append_html_to_node(node: nodes.Element, ad_code: str) -> None:

node.append(html_node)
node.replace_self(node)

return None
6 changes: 3 additions & 3 deletions src/django_docutils/lib/views.py
Expand Up @@ -8,7 +8,8 @@
from django.views.generic.base import ContextMixin, TemplateView
from docutils import nodes

from .._internal.types import StrPath
from django_docutils._internal.types import StrPath

from .publisher import (
publish_doctree,
publish_html_from_doctree,
Expand Down Expand Up @@ -85,8 +86,7 @@ def get_base_template(self) -> str:
"""TODO: move this out of RSTMixin, it is AMP related, not RST."""
if self.request.GET.get("is_amp", False):
return "django_docutils/base-amp.html"
else:
return "base.html"
return "base.html"


class RSTRawView(TemplateTitleView):
Expand Down
3 changes: 1 addition & 2 deletions src/django_docutils/template.py
Expand Up @@ -45,8 +45,7 @@ def get_template(self, template_name: str) -> "_EngineTemplate":
continue

return DocutilsTemplate(template_code, self.options)
else:
raise TemplateDoesNotExist(template_name)
raise TemplateDoesNotExist(template_name)


class DocutilsTemplate:
Expand Down
4 changes: 2 additions & 2 deletions src/django_docutils/templatetags/django_docutils.py
Expand Up @@ -9,7 +9,7 @@
from django.utils.encoding import force_str
from django.utils.safestring import SafeString, mark_safe

from ..lib.publisher import publish_html_from_source
from django_docutils.lib.publisher import publish_html_from_source

register = template.Library()

Expand Down Expand Up @@ -123,7 +123,7 @@ def rst(parser: Parser, token: Token) -> ReStructuredTextNode:
for bit in bits:
match = kwarg_re.match(bit)
if not match:
raise MalformedArgumentsToRSTTag()
raise MalformedArgumentsToRSTTag

name, value = match.groups()
if name:
Expand Down
10 changes: 4 additions & 6 deletions src/django_docutils/views.py
Expand Up @@ -25,7 +25,7 @@ def __init__(
status: t.Optional[int] = None,
charset: t.Optional[str] = None,
using: t.Optional[str] = None,
):
) -> None:
self.rst_name = rst
super().__init__(
request,
Expand All @@ -50,8 +50,7 @@ def rendered_content(self) -> str:
)

template = self.resolve_template(self.template_name)
content = template.render(context)
return content
return template.render(context)


class DocutilsViewRstNameImproperlyConfigured(ImproperlyConfigured):
Expand Down Expand Up @@ -95,6 +94,5 @@ def render_to_response(
def get_rst_names(self) -> t.List[str]:
"""Follows after get_template_names, but for scanning for rst content."""
if self.rst_name is None:
raise DocutilsViewRstNameImproperlyConfigured()
else:
return [self.rst_name]
raise DocutilsViewRstNameImproperlyConfigured
return [self.rst_name]
2 changes: 1 addition & 1 deletion tests/test_docutils_roles.py
Expand Up @@ -52,7 +52,7 @@ def test_register_django_docutils_roles(monkeypatch: pytest.MonkeyPatch) -> None
from django_docutils.lib.roles import registry as roles_registry_pkg

assert roles_registry_pkg.DJANGO_DOCUTILS_LIB_RST, ( # type:ignore[attr-defined]
"Sanity-check, something truthy should be set." ""
"Sanity-check, something truthy should be set."
)
register_django_docutils_roles()

Expand Down

0 comments on commit bec4723

Please sign in to comment.