Skip to content

Commit

Permalink
fix ruff 0.9.0 preview errors and re-format
Browse files Browse the repository at this point in the history
  • Loading branch information
ilius committed Jan 10, 2025
1 parent 7d1f001 commit e697b64
Show file tree
Hide file tree
Showing 27 changed files with 63 additions and 100 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
ls -l
- name: Download ruff
run: |
wget -c https://github.com/astral-sh/ruff/releases/download/0.8.3/ruff-x86_64-unknown-linux-gnu.tar.gz
wget -c https://github.com/astral-sh/ruff/releases/download/0.9.0/ruff-x86_64-unknown-linux-gnu.tar.gz
tar -xzf ruff-*.tar.gz
mv ruff-x86_64-unknown-linux-gnu/ruff .
ls -l ruff
Expand Down
5 changes: 1 addition & 4 deletions pyglossary/entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,10 +248,7 @@ def getFileName(self) -> str: # noqa: PLR6301
return ""

def __repr__(self) -> str:
return (
f"Entry({self._word!r}, {self._defi!r}, "
f"defiFormat={self._defiFormat!r})"
)
return f"Entry({self._word!r}, {self._defi!r}, defiFormat={self._defiFormat!r})"

@property
def s_word(self) -> str:
Expand Down
3 changes: 1 addition & 2 deletions pyglossary/glossary.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ def __init__(
if info:
if not isinstance(info, dict):
raise TypeError(
"Glossary: `info` has invalid type"
", dict or OrderedDict expected",
"Glossary: `info` has invalid type, dict or OrderedDict expected",
)
for key, value in info.items():
self.setInfo(key, value)
Expand Down
6 changes: 2 additions & 4 deletions pyglossary/glossary_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,7 @@ def __init__(
if info:
if not isinstance(info, dict):
raise TypeError(
"Glossary: `info` has invalid type"
", dict or OrderedDict expected",
"Glossary: `info` has invalid type, dict or OrderedDict expected",
)
warnings.warn(
"info= argument is deprecated. Use glos.setInfo(key, value)",
Expand Down Expand Up @@ -1076,8 +1075,7 @@ def _resolveSortParams(
sqlite = self._config.get("auto_sqlite", True)
if sqlite:
log.info(
"Automatically switching to SQLite mode"
f" for writing {plugin.name}",
f"Automatically switching to SQLite mode for writing {plugin.name}",
)

sortKeyTuple = self._checkSortKey(
Expand Down
3 changes: 1 addition & 2 deletions pyglossary/langs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,7 @@ def load(self) -> None:
)

log.debug(
f"LangDict: loaded, {len(self)} keys, "
f"took {(now() - t0) * 1000:.1f} ms",
f"LangDict: loaded, {len(self)} keys, took {(now() - t0) * 1000:.1f} ms",
)

def __getitem__(self, key: str) -> Lang | None:
Expand Down
9 changes: 3 additions & 6 deletions pyglossary/plugin_prop.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,8 +413,7 @@ def checkModule(self, module: Any) -> None: # noqa: ANN401

if not isinstance(self.writeDepends, dict):
log.error(
f"invalid depends={self.writeDepends}"
f" in {self.name!r}.Reader class",
f"invalid depends={self.writeDepends} in {self.name!r}.Reader class",
)

for name, opt in self.optionsProp.items():
Expand Down Expand Up @@ -475,8 +474,7 @@ def checkReaderClass(self) -> bool:
):
if not hasattr(cls, attr):
log.error(
f"Invalid Reader class in {self.name!r} plugin"
f", no {attr!r} method",
f"Invalid Reader class in {self.name!r} plugin, no {attr!r} method",
)
self._Reader = None
return False
Expand All @@ -493,8 +491,7 @@ def checkWriterClass(self) -> bool:
):
if not hasattr(cls, attr):
log.error(
f"Invalid Writer class in {self.name!r} plugin"
f", no {attr!r} method",
f"Invalid Writer class in {self.name!r} plugin, no {attr!r} method",
)
self._Writer = None
return False
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/plugins/appledict/_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ def remove_style(tag: dict, line: str) -> None:


def fix_sound_link(href: str, tag: dict[str, Any]) -> None:
tag["href"] = f'javascript:new Audio("{href[len("sound://"):]}").play();'
tag["href"] = f'javascript:new Audio("{href[len("sound://") :]}").play();'


def link_is_url(href: str) -> bool:
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/plugins/appledict_bin/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ def getChunkLenOffset(
try:
(chunkLen,) = unpack("i", bs)
except Exception as e:
log.error(f"{buffer[pos:pos + 100]!r}")
log.error(f"{buffer[pos : pos + 100]!r}")
raise e from None
return chunkLen, offset

Expand Down
20 changes: 5 additions & 15 deletions pyglossary/plugins/babylon_bgl/bgl_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING, Any

from pyglossary import gregorian
Expand All @@ -40,22 +41,11 @@
__all__ = ["charsetInfoDecode", "infoType3ByCode"]


@dataclass(slots=True)
class InfoItem:
__slots__ = (
"attr",
"decode",
"name",
)

def __init__(
self,
name: str,
decode: Callable[[bytes], Any] | None = None,
attr: bool = False,
) -> None:
self.name = name
self.decode = decode
self.attr = attr
name: str
decode: Callable[[bytes], Any] | None = None
attr: bool = False


def decodeBglBinTime(b_value: bytes) -> str:
Expand Down
3 changes: 1 addition & 2 deletions pyglossary/plugins/babylon_bgl/bgl_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,8 +315,7 @@ def stripDollarIndexes(b_word: bytes) -> tuple[bytes, int]:
# Ihre$1$Ihres
if d1 + 1 < len(b_word) and b_word[d1 + 1] != 0x20:
log.debug(
f"stripDollarIndexes({b_word!r}):\n"
"second $ is followed by non-space",
f"stripDollarIndexes({b_word!r}):\nsecond $ is followed by non-space",
)
b_word_main += b_word[i:d0]
i = d1 + 1
Expand Down
9 changes: 3 additions & 6 deletions pyglossary/plugins/babylon_bgl/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,7 @@ def __init__(self) -> None:

def __str__(self) -> str:
return (
f"Block type={self.type}, length={self.length}, "
f"len(data)={len(self.data)}"
f"Block type={self.type}, length={self.length}, len(data)={len(self.data)}"
)


Expand Down Expand Up @@ -470,8 +469,7 @@ def readInfo(self) -> None: # noqa: PLR0912
# self.bgl_numEntries may be less than the number of entries
# we've read.
log.warning(
f"bgl_numEntries={self.bgl_numEntries}"
f", numEntries={self.numEntries}",
f"bgl_numEntries={self.bgl_numEntries}, numEntries={self.numEntries}",
)

self.numBlocks = 0
Expand Down Expand Up @@ -614,8 +612,7 @@ def readBytes(self, num: int) -> int:
return -1
if len(buf) != num:
log.error(
f"readBytes: expected to read {num} bytes"
f", but found {len(buf)} bytes",
f"readBytes: expected to read {num} bytes, but found {len(buf)} bytes",
)
return -1
return uintFromBytes(buf)
Expand Down
13 changes: 7 additions & 6 deletions pyglossary/plugins/babylon_bgl/reader_debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import gzip
import os
import re
from dataclasses import dataclass
from os.path import join

from pyglossary.core import log
Expand Down Expand Up @@ -52,16 +53,16 @@ def __init__(self) -> None:
self.bglHeader = None # data before gzip header


@dataclass
class MetaDataBlock:
def __init__(self, data: bytes, type_: str) -> None:
self.data = data
self.type = type_
data: bytes
type: str


@dataclass
class MetaDataRange:
def __init__(self, type_: str, count: int) -> None:
self.type = type_
self.count = count
type: str
count: int


class MetaData2:
Expand Down
3 changes: 1 addition & 2 deletions pyglossary/plugins/dict_cc/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,7 @@ def iterRows(
if self._cur is None:
raise ValueError("cur is None")
self._cur.execute(
f"select {column1}, {column2}, entry_type from main_ft"
f" order by {column1}",
f"select {column1}, {column2}, entry_type from main_ft order by {column1}",
)
for row in self._cur.fetchall():
term1 = row[0]
Expand Down
3 changes: 1 addition & 2 deletions pyglossary/plugins/dict_cc_split/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ def iterRows(
if self._cur is None:
raise ValueError("cur is None")
self._cur.execute(
f"select {column1}, {column2}, entry_type from main_ft"
f" order by {column1}",
f"select {column1}, {column2}, entry_type from main_ft order by {column1}",
)
for row in self._cur.fetchall():
term1 = row[0]
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/plugins/dsl/lex.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ def lexRefText(tr: TransformerType) -> tuple[LexType, ErrorType]:
if not target:
target = text

tr.addHtml(f'<a href={quoteattr("bword://" + target)}>{escape(text)}</a>')
tr.addHtml(f"<a href={quoteattr('bword://' + target)}>{escape(text)}</a>")
tr.resetBuf()
return lexRoot, None

Expand Down
3 changes: 1 addition & 2 deletions pyglossary/plugins/ebook_kobo/writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,7 @@ def writeGroup(lastPrefix: str) -> None:
htmlContents += "</html>"
core.trace(
log,
f"writeGroup: {lastPrefix!r}, "
f"{group_fname!r}, count={groupCounter}",
f"writeGroup: {lastPrefix!r}, {group_fname!r}, count={groupCounter}",
)
with gzip.open(group_fname + ".html", mode="wb") as gzipFile:
gzipFile.write(htmlContents.encode("utf-8"))
Expand Down
5 changes: 1 addition & 4 deletions pyglossary/plugins/html_dir/writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,10 +467,7 @@ def addLinks(text: str, pos: int) -> None:
tmpFilename = escapeNTB(self._filenameList[-1])
for word in entry.l_word:
indexTxtFileObj.write(
f"{entryIndex}\t"
f"{escapeNTB(word)}\t"
f"{tmpFilename}\t"
f"{pos}\n",
f"{entryIndex}\t{escapeNTB(word)}\t{tmpFilename}\t{pos}\n",
)
del tmpFilename
text = replaceBword(text)
Expand Down
37 changes: 17 additions & 20 deletions pyglossary/plugins/quickdic6/commons.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,26 +34,23 @@
"""Second part of Java serialization of java.util.HashSet"""

LINKED_HASH_SET_INIT = (
(
b"\xac\xed" # magic
b"\x00\x05" # version
b"\x73" # object
b"\x72" # class
# Java String "java.util.LinkedHashSet":
b"\x00\x17\x6a\x61\x76\x61\x2e\x75\x74\x69"
b"\x6c\x2e\x4c\x69\x6e\x6b\x65\x64"
b"\x48\x61\x73\x68\x53\x65\x74"
# serialization ID:
b"\xd8\x6c\xd7\x5a\x95\xdd\x2a\x1e"
b"\x02" # flags
b"\x00\x00" # fields count
b"\x78" # blockdata end
b"\x72" # superclass (java.util.HashSet)
b"\x00\x11\x6a\x61\x76\x61\x2e\x75\x74\x69"
b"\x6c\x2e\x48\x61\x73\x68\x53\x65\x74"
)
+ HASH_SET_INIT2
)
b"\xac\xed" # magic
b"\x00\x05" # version
b"\x73" # object
b"\x72" # class
# Java String "java.util.LinkedHashSet":
b"\x00\x17\x6a\x61\x76\x61\x2e\x75\x74\x69"
b"\x6c\x2e\x4c\x69\x6e\x6b\x65\x64"
b"\x48\x61\x73\x68\x53\x65\x74"
# serialization ID:
b"\xd8\x6c\xd7\x5a\x95\xdd\x2a\x1e"
b"\x02" # flags
b"\x00\x00" # fields count
b"\x78" # blockdata end
b"\x72" # superclass (java.util.HashSet)
b"\x00\x11\x6a\x61\x76\x61\x2e\x75\x74\x69"
b"\x6c\x2e\x48\x61\x73\x68\x53\x65\x74"
) + HASH_SET_INIT2
"""Header of Java serialization of java.util.LinkedHashSet"""

HASH_SET_CAPACITY_FACTOR = 0.75
Expand Down
5 changes: 1 addition & 4 deletions pyglossary/plugins/quickdic6/writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,7 @@
":: Lower; 'ae' > 'ä'; 'oe' > 'ö'; 'ue' > 'ü'; 'ß' > 'ss'; "
)
default_normalizer_rules = (
":: Any-Latin; ' ' > ; "
":: Lower; :: NFD; "
":: [:Nonspacing Mark:] Remove; "
":: NFC ;"
":: Any-Latin; ' ' > ; :: Lower; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC ;"
)


Expand Down
3 changes: 1 addition & 2 deletions pyglossary/plugins/stardict/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,8 +406,7 @@ def readSynFile(self) -> dict[int, list[str]]:
pos += 4
if entryIndex >= self._wordCount:
log.error(
"Corrupted synonym file. "
f"Word {b_alt!r} references invalid item",
f"Corrupted synonym file. Word {b_alt!r} references invalid item",
)
continue

Expand Down
3 changes: 1 addition & 2 deletions pyglossary/ui/argparse_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,7 @@ def validateFlags(args: argparse.Namespace, log: logging.Logger) -> bool:
if args.sortKeyName and not lookupSortKey(args.sortKeyName):
valuesStr = ", ".join(_sk.name for _sk in namedSortKeyList)
log.critical(
f"Invalid sortKeyName={args.sortKeyName!r}"
f". Supported values:\n{valuesStr}",
f"Invalid sortKeyName={args.sortKeyName!r}. Supported values:\n{valuesStr}",
)
return False

Expand Down
6 changes: 3 additions & 3 deletions pyglossary/ui/ui_web/websocket_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,9 +367,9 @@ def send_close(self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON):
header = bytearray()
payload = struct.pack("!H", status) + reason
payload_length = len(payload)
assert (
payload_length <= 125
), "We only support short closing reasons at the moment"
assert payload_length <= 125, (
"We only support short closing reasons at the moment"
)

# Send CLOSE with status & reason
header.append(FIN | OPCODE_CLOSE_CONN)
Expand Down
4 changes: 2 additions & 2 deletions pyglossary/ui/ui_web/websocket_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def new_client(client, server):

# Called on client disconnecting
def client_left(client, server):
log.info(f'{server}: Client({(client and client.get("id")) or -1}) disconnected')
log.info(f"{server}: Client({(client and client.get('id')) or -1}) disconnected")


# Callback invoked when client sends a message
Expand Down Expand Up @@ -108,7 +108,7 @@ def browse_check_entry(entry: EntryType, wordQuery: str) -> str | None:
extension = Path(entry.s_word).suffix[1:]
html_entry += f"""
<img class="data"
src="data:image/{extension};base64,{base64.b64encode(entry.data).decode('utf-8')}"
src="data:image/{extension};base64,{base64.b64encode(entry.data).decode("utf-8")}"
alt="{entry.s_word}"/>
"""
return html_entry
Expand Down
3 changes: 1 addition & 2 deletions tests/deprecated/glossary_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,7 @@ def downloadFile(self, filename):
actual_crc32 = crc32hex(data)
if actual_crc32 != crc32:
raise RuntimeError(
"CRC32 check failed for downloaded file: "
f"{filename}: {actual_crc32}",
f"CRC32 check failed for downloaded file: {filename}: {actual_crc32}",
)
with open(fpath, mode="wb") as _file:
_file.write(data)
Expand Down
4 changes: 3 additions & 1 deletion tests/g_ebook_epub2_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ def convert_to_epub(
)

if sha1sum:
os.environ["EPUB_UUID"] = hashlib.sha1(inputFname.encode("ascii")).hexdigest()
os.environ["EPUB_UUID"] = hashlib.sha1(
inputFname.encode("ascii")
).hexdigest()
os.environ["EBOOK_CREATION_TIME"] = "1730579400"
# print(f'{os.environ["EPUB_UUID"]=}')

Expand Down
Loading

0 comments on commit e697b64

Please sign in to comment.