Skip to content

Commit

Permalink
More ruff checks, and make it fix
Browse files Browse the repository at this point in the history
  • Loading branch information
boxydog committed Nov 5, 2023
1 parent dc1b6ab commit 413d5a1
Show file tree
Hide file tree
Showing 28 changed files with 186 additions and 120 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ repos:
rev: v0.1.3
hooks:
- id: ruff
args: ["--fix"]
- id: ruff-format
args: ["--check"]

exclude: ^pelican/tests/output/
14 changes: 6 additions & 8 deletions pelican/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@

# pelican.log has to be the first pelican module to be loaded
# because logging.setLoggerClass has to be called before logging.getLogger
from pelican.log import console
from pelican.log import console # noqa: I001
from pelican.log import init as init_logging
from pelican.generators import (
ArticlesGenerator, # noqa: I100
ArticlesGenerator,
PagesGenerator,
SourceFileGenerator,
StaticGenerator,
Expand Down Expand Up @@ -273,7 +273,7 @@ def __call__(self, parser, namespace, values, option_string):
)
)
else:
console.print("\n{} is not a recognized setting.".format(setting))
console.print(f"\n{setting} is not a recognized setting.")
break
else:
# No argument was given to --print-settings, so print all settings
Expand Down Expand Up @@ -344,8 +344,8 @@ def parse_arguments(argv=None):
"--settings",
dest="settings",
help="The settings of the application, this is "
"automatically set to {} if a file exists with this "
"name.".format(DEFAULT_CONFIG_NAME),
f"automatically set to {DEFAULT_CONFIG_NAME} if a file exists with this "
"name.",
)

parser.add_argument(
Expand Down Expand Up @@ -611,9 +611,7 @@ def listen(server, port, output, excqueue=None):
return

try:
console.print(
"Serving site at: http://{}:{} - Tap CTRL-C to stop".format(server, port)
)
console.print(f"Serving site at: http://{server}:{port} - Tap CTRL-C to stop")
httpd.serve_forever()
except Exception as e:
if excqueue is not None:
Expand Down
1 change: 0 additions & 1 deletion pelican/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,5 @@

from . import main


if __name__ == "__main__":
main()
15 changes: 7 additions & 8 deletions pelican/contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

from pelican.plugins import signals
from pelican.settings import DEFAULT_CONFIG

# Import these so that they're available when you import from pelican.contents.
from pelican.urlwrappers import Author, Category, Tag, URLWrapper # NOQA
from pelican.utils import (
deprecated_attribute,
memoized,
Expand All @@ -27,9 +30,6 @@
truncate_html_words,
)

# Import these so that they're available when you import from pelican.contents.
from pelican.urlwrappers import Author, Category, Tag, URLWrapper # NOQA

logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -235,7 +235,7 @@ def url_format(self):
def _expand_settings(self, key, klass=None):
if not klass:
klass = self.__class__.__name__
fq_key = ("{}_{}".format(klass, key)).upper()
fq_key = (f"{klass}_{key}").upper()
return str(self.settings[fq_key]).format(**self.url_format)

def get_url_setting(self, key):
Expand Down Expand Up @@ -361,13 +361,13 @@ def _find_path(path):

def _get_intrasite_link_regex(self):
intrasite_link_regex = self.settings["INTRASITE_LINK_REGEX"]
regex = r"""
regex = rf"""
(?P<markup><[^\>]+ # match tag with all url-value attributes
(?:href|src|poster|data|cite|formaction|action|content)\s*=\s*)
(?P<quote>["\']) # require value to be quoted
(?P<path>{}(?P<value>.*?)) # the url value
(?P=quote)""".format(intrasite_link_regex)
(?P<path>{intrasite_link_regex}(?P<value>.*?)) # the url value
(?P=quote)"""
return re.compile(regex, re.X)

def _update_content(self, content, siteurl):
Expand Down Expand Up @@ -456,7 +456,6 @@ def _get_summary(self):
@summary.setter
def summary(self, value):
"""Dummy function"""
pass

@property
def status(self):
Expand Down
2 changes: 1 addition & 1 deletion pelican/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from rich.console import Console
from rich.logging import RichHandler

__all__ = ["init"]
__all__ = ["init", "console"]

console = Console()

Expand Down
2 changes: 1 addition & 1 deletion pelican/paginator.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def __init__(self, name, url, object_list, number, paginator, settings):
self.settings = settings

def __repr__(self):
return "<Page {} of {}>".format(self.number, self.paginator.num_pages)
return f"<Page {self.number} of {self.paginator.num_pages}>"

def has_next(self):
return self.number < self.paginator.num_pages
Expand Down
9 changes: 4 additions & 5 deletions pelican/plugins/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import pkgutil
import sys


logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -49,7 +48,7 @@ def plugin_enabled(name, plugin_list=None):
# search name as is
return True

if "pelican.plugins.{}".format(name) in plugin_list:
if f"pelican.plugins.{name}" in plugin_list:
# check if short name is a namespace plugin
return True

Expand All @@ -68,7 +67,7 @@ def load_legacy_plugin(plugin, plugin_paths):
# If failed, try to find it in normal importable locations
spec = importlib.util.find_spec(plugin)
if spec is None:
raise ImportError("Cannot import plugin `{}`".format(plugin))
raise ImportError(f"Cannot import plugin `{plugin}`")
else:
# Avoid loading the same plugin twice
if spec.name in sys.modules:
Expand Down Expand Up @@ -106,8 +105,8 @@ def load_plugins(settings):
# try to find in namespace plugins
if plugin in namespace_plugins:
plugin = namespace_plugins[plugin]
elif "pelican.plugins.{}".format(plugin) in namespace_plugins:
plugin = namespace_plugins["pelican.plugins.{}".format(plugin)]
elif f"pelican.plugins.{plugin}" in namespace_plugins:
plugin = namespace_plugins[f"pelican.plugins.{plugin}"]
# try to import it
else:
try:
Expand Down
2 changes: 1 addition & 1 deletion pelican/plugins/signals.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from blinker import signal, Signal
from blinker import Signal, signal
from ordered_set import OrderedSet

# Signals will call functions in the order of connection, i.e. plugin order
Expand Down
20 changes: 10 additions & 10 deletions pelican/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
try:
from markdown import Markdown
except ImportError:
Markdown = False # NOQA
Markdown = False

# Metadata processors have no way to discard an unwanted value, so we have
# them return this value instead to signal that it should be discarded later.
Expand Down Expand Up @@ -401,7 +401,7 @@ def handle_endtag(self, tag):
self._in_body = False
self._in_top_level = True
elif self._in_body:
self._data_buffer += "</{}>".format(escape(tag))
self._data_buffer += f"</{escape(tag)}>"

def handle_startendtag(self, tag, attrs):
if tag == "meta" and self._in_head:
Expand All @@ -410,36 +410,36 @@ def handle_startendtag(self, tag, attrs):
self._data_buffer += self.build_tag(tag, attrs, True)

def handle_comment(self, data):
self._data_buffer += "<!--{}-->".format(data)
self._data_buffer += f"<!--{data}-->"

def handle_data(self, data):
self._data_buffer += data

def handle_entityref(self, data):
self._data_buffer += "&{};".format(data)
self._data_buffer += f"&{data};"

def handle_charref(self, data):
self._data_buffer += "&#{};".format(data)
self._data_buffer += f"&#{data};"

def build_tag(self, tag, attrs, close_tag):
result = "<{}".format(escape(tag))
result = f"<{escape(tag)}"
for k, v in attrs:
result += " " + escape(k)
if v is not None:
# If the attribute value contains a double quote, surround
# with single quotes, otherwise use double quotes.
if '"' in v:
result += "='{}'".format(escape(v, quote=False))
result += f"='{escape(v, quote=False)}'"
else:
result += '="{}"'.format(escape(v, quote=False))
result += f'="{escape(v, quote=False)}"'
if close_tag:
return result + " />"
return result + ">"

def _handle_meta_tag(self, attrs):
name = self._attr_value(attrs, "name")
if name is None:
attr_list = ['{}="{}"'.format(k, v) for k, v in attrs]
attr_list = [f'{k}="{v}"' for k, v in attrs]
attr_serialized = ", ".join(attr_list)
logger.warning(
"Meta tag in file %s does not have a 'name' "
Expand Down Expand Up @@ -607,8 +607,8 @@ def read_file(

# eventually filter the content with typogrify if asked so
if self.settings["TYPOGRIFY"]:
from typogrify.filters import typogrify
import smartypants
from typogrify.filters import typogrify

typogrify_dashes = self.settings["TYPOGRIFY_DASHES"]
if typogrify_dashes == "oldschool":
Expand Down
1 change: 0 additions & 1 deletion pelican/rstdirectives.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from docutils import nodes, utils
from docutils.parsers.rst import Directive, directives, roles

from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import TextLexer, get_lexer_by_name
Expand Down
12 changes: 5 additions & 7 deletions pelican/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,11 +261,9 @@ def _printf_s_to_format_field(printf_string, format_field):
TEST_STRING = "PELICAN_PRINTF_S_DEPRECATION"
expected = printf_string % TEST_STRING

result = printf_string.replace("{", "{{").replace("}", "}}") % "{{{}}}".format(
format_field
)
result = printf_string.replace("{", "{{").replace("}", "}}") % f"{{{format_field}}}"
if result.format(**{format_field: TEST_STRING}) != expected:
raise ValueError("Failed to safely replace %s with {{{}}}".format(format_field))
raise ValueError(f"Failed to safely replace %s with {{{format_field}}}")

return result

Expand Down Expand Up @@ -350,9 +348,9 @@ def handle_deprecated_settings(settings):
),
]:
if old in settings:
message = "The {} setting has been removed in favor of {}".format(old, new)
message = f"The {old} setting has been removed in favor of {new}"
if doc:
message += ", see {} for details".format(doc)
message += f", see {doc} for details"
logger.warning(message)

# PAGINATED_DIRECT_TEMPLATES -> PAGINATED_TEMPLATES
Expand Down Expand Up @@ -406,7 +404,7 @@ def handle_deprecated_settings(settings):
)
logger.warning(message)
if old_values.get("SLUG"):
for f in {"CATEGORY", "TAG"}:
for f in ("CATEGORY", "TAG"):
if old_values.get(f):
old_values[f] = old_values["SLUG"] + old_values[f]
old_values["AUTHOR"] = old_values.get("AUTHOR", [])
Expand Down
2 changes: 1 addition & 1 deletion pelican/tests/build_test/test_build_files.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from re import match
import tarfile
from pathlib import Path
from re import match
from zipfile import ZipFile

import pytest
Expand Down
6 changes: 2 additions & 4 deletions pelican/tests/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def skipIfNoExecutable(executable):
res = None

if res is None:
return unittest.skip("{} executable not found".format(executable))
return unittest.skip(f"{executable} executable not found")

return lambda func: func

Expand Down Expand Up @@ -261,9 +261,7 @@ def assertLogCountEqual(self, count=None, msg=None, **kwargs):
self.assertEqual(
actual,
count,
msg="expected {} occurrences of {!r}, but found {}".format(
count, msg, actual
),
msg=f"expected {count} occurrences of {msg!r}, but found {actual}",
)


Expand Down
1 change: 0 additions & 1 deletion pelican/tests/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from pelican.generators import ArticlesGenerator, PagesGenerator
from pelican.tests.support import get_context, get_settings, unittest


CUR_DIR = os.path.dirname(__file__)
CONTENT_DIR = os.path.join(CUR_DIR, "content")

Expand Down
2 changes: 0 additions & 2 deletions pelican/tests/test_contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from pelican.tests.support import LoggedTestCase, get_context, get_settings, unittest
from pelican.utils import path_to_url, posixize_path, truncate_html_words


# generate one paragraph, enclosed with <p>
TEST_CONTENT = str(generate_lorem_ipsum(n=1))
TEST_SUMMARY = generate_lorem_ipsum(n=1, html=False)
Expand Down Expand Up @@ -297,7 +296,6 @@ def test_template(self):
def test_signal(self):
def receiver_test_function(sender):
receiver_test_function.has_been_called = True
pass

receiver_test_function.has_been_called = False

Expand Down
2 changes: 1 addition & 1 deletion pelican/tests/test_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@
TemplatePagesGenerator,
)
from pelican.tests.support import (
TestCaseWithCLocale,
can_symlink,
get_context,
get_settings,
unittest,
TestCaseWithCLocale,
)
from pelican.writers import Writer

Expand Down
8 changes: 3 additions & 5 deletions pelican/tests/test_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

from pelican.settings import DEFAULT_CONFIG
from pelican.tests.support import (
TestCaseWithCLocale,
mute,
skipIfNoExecutable,
temporary_folder,
unittest,
TestCaseWithCLocale,
)
from pelican.tools.pelican_import import (
blogger2fields,
Expand Down Expand Up @@ -37,7 +37,7 @@
try:
from bs4 import BeautifulSoup
except ImportError:
BeautifulSoup = False # NOQA
BeautifulSoup = False

try:
import bs4.builder._lxml as LXML
Expand Down Expand Up @@ -528,9 +528,7 @@ def test_attachments_associated_with_correct_post(self):
self.assertEqual(self.attachments[post], {expected_invalid})
else:
self.fail(
"all attachments should match to a " "filename or None, {}".format(
post
)
"all attachments should match to a " f"filename or None, {post}"
)

def test_download_attachments(self):
Expand Down
1 change: 0 additions & 1 deletion pelican/tests/test_paginator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from pelican.settings import DEFAULT_CONFIG
from pelican.tests.support import get_settings, unittest


# generate one paragraph, enclosed with <p>
TEST_CONTENT = str(generate_lorem_ipsum(n=1))
TEST_SUMMARY = generate_lorem_ipsum(n=1, html=False)
Expand Down
Loading

0 comments on commit 413d5a1

Please sign in to comment.