Skip to content

Commit

Permalink
Linting and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
yaph committed Nov 5, 2024
1 parent 33962ca commit 4974416
Show file tree
Hide file tree
Showing 13 changed files with 30 additions and 45 deletions.
5 changes: 1 addition & 4 deletions logya/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ def create_url(path: Path) -> str:
suffix = ''
if path.suffix in remove_extensions:
suffix = '/'
if path.stem == 'index':
path = Path(path.parent)
else:
path = path.parent.joinpath(path.stem)
path = Path(path.parent) if path.stem == 'index' else path.parent.joinpath(path.stem)

if not path.parts:
return '/'
Expand Down
2 changes: 1 addition & 1 deletion logya/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def update_collections(self, doc: dict):

# Add attribute for creating collection links in templates.
links = attr + '_links'
doc[links] = doc.get(links, []) + [(url, value)]
doc[links] = [*doc.get(links, []), (url, value)]

# Update or create collection index value.
if coll_data := coll['index'].get(url):
Expand Down
2 changes: 1 addition & 1 deletion logya/docparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def parse(content, content_type=None):
header_end = lines[header_start:].index('---') + 1
header = '\n'.join(lines[header_start:header_end])
body = '\n'.join(lines[header_end + 1:]).strip()
parsed = load(header, Loader=Loader)
parsed = load(header, Loader=Loader) # noqa: S506

# Parse body if not HTML/XML.
if body and content_type == 'markdown':
Expand Down
2 changes: 1 addition & 1 deletion logya/encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.date | datetime.datetime):
return obj.isoformat(sep=' ', timespec='seconds')
elif isinstance(obj, datetime.timedelta):
if isinstance(obj, datetime.timedelta):
return (datetime.datetime.min + obj).time().isoformat(sep=' ', timespec='seconds')

return json.JSONEncoder.default(self, obj)
10 changes: 6 additions & 4 deletions logya/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ class HTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
L: Logya

def __init__(self, *args):
super(HTTPRequestHandler, self).__init__(*args, directory=self.L.paths.public.as_posix())
super().__init__(*args, directory=self.L.paths.public.as_posix())

def do_GET(self):
def do_GET(self): # noqa: N802
update_resource(self.path, self.L)
super(HTTPRequestHandler, self).do_GET()
super().do_GET()


def update_page(url: str, L: Logya):
def update_page(url: str, L: Logya) -> bool:
"""Update content or collection page."""

if content := L.doc_index.get(url):
Expand All @@ -39,6 +39,8 @@ def update_page(url: str, L: Logya):
L.info(f'Refreshed collection: {url}')
return True

return False


def update_resource(path: str, L: Logya) -> None:
"""Update resource corresponding to given url.
Expand Down
7 changes: 4 additions & 3 deletions logya/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from logya.util import cache, slugify

env = Environment(
autoescape=True,
lstrip_blocks=True,
trim_blocks=True
)
Expand All @@ -31,9 +32,9 @@ def _alpha_index(
key = value.lower()[0]
if key not in ascii_lowercase:
key = non_ascii_key
index[key] = index.get(key, []) + [item]
index[key] = [*index.get(key, []), item]

reverse = False if sort_order == 'ascending' else True
reverse = (sort_order == 'ascending')
keys = sorted(index.keys(), reverse=reverse)
return {key: sorted(index[key], key=itemgetter(sort_attr)) for key in keys}

Expand Down Expand Up @@ -78,7 +79,7 @@ def _get_docs(L, url: str, sort_attr: str = 'created', sort_order: str = 'descen
if doc_url.startswith(url):
docs.append(content['doc'])

reverse = True if sort_order == 'descending' else False
reverse = (sort_order == 'descending')
return sorted((d for d in docs if sort_attr in d), key=lambda item: _sort_docs(item, sort_attr), reverse=reverse)


Expand Down
12 changes: 9 additions & 3 deletions logya/util.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import re
from collections import namedtuple
from pathlib import Path
from string import punctuation, whitespace
from typing import NamedTuple

from yaml import dump, load

Expand All @@ -16,7 +16,13 @@
forbidden = (set(punctuation) - set('+-_.,@')) | set(whitespace)
re_forbidden = re.compile(f'[{re.escape("".join(forbidden))}]+')

Paths = namedtuple('Paths', ['root', 'content', 'public', 'static', 'templates'])
# For accessing site paths.
class Paths(NamedTuple):
root: str
content: str
public: str
static: str
templates: str


def cache(func):
Expand All @@ -41,7 +47,7 @@ def encode_content(headers: dict, body: str) -> str:
def load_yaml(text: str) -> dict:
"""Wrapper for yaml.load so yaml import is done only once."""

return load(text, Loader=Loader)
return load(text, Loader=Loader) # noqa: S506


def paths(dir_site: str) -> Paths:
Expand Down
9 changes: 6 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ dependencies = [
logya = "logya.main:main"

[project.urls]
Documentation = "https://github.com/yaph/logya#readme"
Documentation = "https://ramiro.org/logya/docs/"
Issues = "https://github.com/yaph/logya/issues"
Source = "https://github.com/yaph/logya"

Expand Down Expand Up @@ -94,8 +94,11 @@ exclude_lines = [
]

[tool.ruff.lint]
ignore = ["T201", "DTZ005", "FA100"]
ignore = ["DTZ006", "FA100", "FBT001", "FBT002", "N803", "N806", "T201"]

[tool.ruff.format]
quote-style = "preserve"
skip-magic-trailing-comma = true
skip-magic-trailing-comma = true

[tool.ruff.lint.per-file-ignores]
"tests/*" = ["INP", "N", "S"]
20 changes: 0 additions & 20 deletions tests/__init__.py

This file was deleted.

2 changes: 0 additions & 2 deletions tests/test_content.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python

from pathlib import Path

import logya.content
Expand Down
1 change: 0 additions & 1 deletion tests/test_core.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#!/usr/bin/env python
import pytest

import logya.core
Expand Down
1 change: 0 additions & 1 deletion tests/test_template.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#!/usr/bin/env python
import pytest

import logya.core
Expand Down
2 changes: 1 addition & 1 deletion tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

def test_encode_content():
text = logya.util.encode_content({}, '')
assert text.count('---\n') == 2
assert text.count('---\n') == 2 # noqa: PLR2004


def test_slugify():
Expand Down

0 comments on commit 4974416

Please sign in to comment.