From e697b64ad3e6c0981974e3360ea44290b979193d Mon Sep 17 00:00:00 2001 From: Saeed Rasooli Date: Fri, 10 Jan 2025 05:40:19 +0330 Subject: [PATCH] fix ruff 0.9.0 preview errors and re-format --- .github/workflows/ruff.yml | 2 +- pyglossary/entry.py | 5 +-- pyglossary/glossary.py | 3 +- pyglossary/glossary_v2.py | 6 +-- pyglossary/langs/__init__.py | 3 +- pyglossary/plugin_prop.py | 9 ++--- pyglossary/plugins/appledict/_content.py | 2 +- pyglossary/plugins/appledict_bin/reader.py | 2 +- pyglossary/plugins/babylon_bgl/bgl_info.py | 20 +++------- pyglossary/plugins/babylon_bgl/bgl_text.py | 3 +- pyglossary/plugins/babylon_bgl/reader.py | 9 ++--- .../plugins/babylon_bgl/reader_debug.py | 13 ++++--- pyglossary/plugins/dict_cc/reader.py | 3 +- pyglossary/plugins/dict_cc_split/reader.py | 3 +- pyglossary/plugins/dsl/lex.py | 2 +- pyglossary/plugins/ebook_kobo/writer.py | 3 +- pyglossary/plugins/html_dir/writer.py | 5 +-- pyglossary/plugins/quickdic6/commons.py | 37 +++++++++---------- pyglossary/plugins/quickdic6/writer.py | 5 +-- pyglossary/plugins/stardict/reader.py | 3 +- pyglossary/ui/argparse_main.py | 3 +- pyglossary/ui/ui_web/websocket_handler.py | 6 +-- pyglossary/ui/ui_web/websocket_main.py | 4 +- tests/deprecated/glossary_test.py | 3 +- tests/g_ebook_epub2_test.py | 4 +- tests/glossary_v2_test.py | 3 +- tests/gregorian_test.py | 2 +- 27 files changed, 63 insertions(+), 100 deletions(-) diff --git a/.github/workflows/ruff.yml b/.github/workflows/ruff.yml index a4a97e85d..1fdf2053e 100644 --- a/.github/workflows/ruff.yml +++ b/.github/workflows/ruff.yml @@ -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 diff --git a/pyglossary/entry.py b/pyglossary/entry.py index 381f3f4e3..5a88b983c 100644 --- a/pyglossary/entry.py +++ b/pyglossary/entry.py @@ -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: diff --git a/pyglossary/glossary.py b/pyglossary/glossary.py index c6030aea6..574e5a777 100644 --- a/pyglossary/glossary.py +++ b/pyglossary/glossary.py @@ -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) diff --git a/pyglossary/glossary_v2.py b/pyglossary/glossary_v2.py index f526e538e..6af43eae5 100644 --- a/pyglossary/glossary_v2.py +++ b/pyglossary/glossary_v2.py @@ -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)", @@ -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( diff --git a/pyglossary/langs/__init__.py b/pyglossary/langs/__init__.py index c35e63122..5275332bc 100644 --- a/pyglossary/langs/__init__.py +++ b/pyglossary/langs/__init__.py @@ -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: diff --git a/pyglossary/plugin_prop.py b/pyglossary/plugin_prop.py index b77ad13dd..b69e17e56 100644 --- a/pyglossary/plugin_prop.py +++ b/pyglossary/plugin_prop.py @@ -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(): @@ -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 @@ -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 diff --git a/pyglossary/plugins/appledict/_content.py b/pyglossary/plugins/appledict/_content.py index f29ceffa9..4ec0092ac 100644 --- a/pyglossary/plugins/appledict/_content.py +++ b/pyglossary/plugins/appledict/_content.py @@ -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: diff --git a/pyglossary/plugins/appledict_bin/reader.py b/pyglossary/plugins/appledict_bin/reader.py index 66a78b5ba..07c58b0cd 100644 --- a/pyglossary/plugins/appledict_bin/reader.py +++ b/pyglossary/plugins/appledict_bin/reader.py @@ -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 diff --git a/pyglossary/plugins/babylon_bgl/bgl_info.py b/pyglossary/plugins/babylon_bgl/bgl_info.py index 74a90ad86..86f0008e2 100644 --- a/pyglossary/plugins/babylon_bgl/bgl_info.py +++ b/pyglossary/plugins/babylon_bgl/bgl_info.py @@ -23,6 +23,7 @@ from __future__ import annotations +from dataclasses import dataclass from typing import TYPE_CHECKING, Any from pyglossary import gregorian @@ -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: diff --git a/pyglossary/plugins/babylon_bgl/bgl_text.py b/pyglossary/plugins/babylon_bgl/bgl_text.py index 03707caa8..8b4d1a84c 100644 --- a/pyglossary/plugins/babylon_bgl/bgl_text.py +++ b/pyglossary/plugins/babylon_bgl/bgl_text.py @@ -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 diff --git a/pyglossary/plugins/babylon_bgl/reader.py b/pyglossary/plugins/babylon_bgl/reader.py index 082a70982..e8f9df728 100644 --- a/pyglossary/plugins/babylon_bgl/reader.py +++ b/pyglossary/plugins/babylon_bgl/reader.py @@ -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)}" ) @@ -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 @@ -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) diff --git a/pyglossary/plugins/babylon_bgl/reader_debug.py b/pyglossary/plugins/babylon_bgl/reader_debug.py index 0bb7a278d..007244826 100644 --- a/pyglossary/plugins/babylon_bgl/reader_debug.py +++ b/pyglossary/plugins/babylon_bgl/reader_debug.py @@ -22,6 +22,7 @@ import gzip import os import re +from dataclasses import dataclass from os.path import join from pyglossary.core import log @@ -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: diff --git a/pyglossary/plugins/dict_cc/reader.py b/pyglossary/plugins/dict_cc/reader.py index dd457c196..3448afacd 100644 --- a/pyglossary/plugins/dict_cc/reader.py +++ b/pyglossary/plugins/dict_cc/reader.py @@ -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] diff --git a/pyglossary/plugins/dict_cc_split/reader.py b/pyglossary/plugins/dict_cc_split/reader.py index d0d2c8085..52d4bab62 100644 --- a/pyglossary/plugins/dict_cc_split/reader.py +++ b/pyglossary/plugins/dict_cc_split/reader.py @@ -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] diff --git a/pyglossary/plugins/dsl/lex.py b/pyglossary/plugins/dsl/lex.py index fdf7e33ff..ea11c50a1 100644 --- a/pyglossary/plugins/dsl/lex.py +++ b/pyglossary/plugins/dsl/lex.py @@ -213,7 +213,7 @@ def lexRefText(tr: TransformerType) -> tuple[LexType, ErrorType]: if not target: target = text - tr.addHtml(f'{escape(text)}') + tr.addHtml(f"{escape(text)}") tr.resetBuf() return lexRoot, None diff --git a/pyglossary/plugins/ebook_kobo/writer.py b/pyglossary/plugins/ebook_kobo/writer.py index d9edc2417..f1103cd46 100644 --- a/pyglossary/plugins/ebook_kobo/writer.py +++ b/pyglossary/plugins/ebook_kobo/writer.py @@ -131,8 +131,7 @@ def writeGroup(lastPrefix: str) -> None: htmlContents += "" 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")) diff --git a/pyglossary/plugins/html_dir/writer.py b/pyglossary/plugins/html_dir/writer.py index a186513bb..cf7563693 100644 --- a/pyglossary/plugins/html_dir/writer.py +++ b/pyglossary/plugins/html_dir/writer.py @@ -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) diff --git a/pyglossary/plugins/quickdic6/commons.py b/pyglossary/plugins/quickdic6/commons.py index ae158b44f..925294eec 100644 --- a/pyglossary/plugins/quickdic6/commons.py +++ b/pyglossary/plugins/quickdic6/commons.py @@ -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 diff --git a/pyglossary/plugins/quickdic6/writer.py b/pyglossary/plugins/quickdic6/writer.py index 00f7b1d42..4daccc77c 100644 --- a/pyglossary/plugins/quickdic6/writer.py +++ b/pyglossary/plugins/quickdic6/writer.py @@ -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 ;" ) diff --git a/pyglossary/plugins/stardict/reader.py b/pyglossary/plugins/stardict/reader.py index a21de2aca..1af1c328f 100644 --- a/pyglossary/plugins/stardict/reader.py +++ b/pyglossary/plugins/stardict/reader.py @@ -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 diff --git a/pyglossary/ui/argparse_main.py b/pyglossary/ui/argparse_main.py index 21aaf1059..318b7a7f3 100644 --- a/pyglossary/ui/argparse_main.py +++ b/pyglossary/ui/argparse_main.py @@ -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 diff --git a/pyglossary/ui/ui_web/websocket_handler.py b/pyglossary/ui/ui_web/websocket_handler.py index 16c102267..5919b7ce1 100644 --- a/pyglossary/ui/ui_web/websocket_handler.py +++ b/pyglossary/ui/ui_web/websocket_handler.py @@ -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) diff --git a/pyglossary/ui/ui_web/websocket_main.py b/pyglossary/ui/ui_web/websocket_main.py index a6a8ae43f..af98f3073 100644 --- a/pyglossary/ui/ui_web/websocket_main.py +++ b/pyglossary/ui/ui_web/websocket_main.py @@ -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 @@ -108,7 +108,7 @@ def browse_check_entry(entry: EntryType, wordQuery: str) -> str | None: extension = Path(entry.s_word).suffix[1:] html_entry += f""" {entry.s_word} """ return html_entry diff --git a/tests/deprecated/glossary_test.py b/tests/deprecated/glossary_test.py index 828f27a94..7d72c7c44 100644 --- a/tests/deprecated/glossary_test.py +++ b/tests/deprecated/glossary_test.py @@ -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) diff --git a/tests/g_ebook_epub2_test.py b/tests/g_ebook_epub2_test.py index 8b476f878..e26d82e61 100644 --- a/tests/g_ebook_epub2_test.py +++ b/tests/g_ebook_epub2_test.py @@ -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"]=}') diff --git a/tests/glossary_v2_test.py b/tests/glossary_v2_test.py index d07a72c8b..fd61dd204 100644 --- a/tests/glossary_v2_test.py +++ b/tests/glossary_v2_test.py @@ -117,8 +117,7 @@ def downloadFile(self, filename): actual_crc32 = crc32hex(data) if actual_crc32 != crc32: raise RuntimeError( - "CRC32 check failed for downloaded file: " - f"{filename!r}: {actual_crc32}", + f"CRC32 check failed for downloaded file: {filename!r}: {actual_crc32}", ) with open(fpath, mode="wb") as _file: _file.write(data) diff --git a/tests/gregorian_test.py b/tests/gregorian_test.py index 86c2f3c46..d162696e6 100644 --- a/tests/gregorian_test.py +++ b/tests/gregorian_test.py @@ -21,7 +21,7 @@ def notest_isLeap_negativeYear(self): for year in range(10, -101, -1): isLeap = isLeapFunc(year) # print(f"{str(year).center(10)} {'L' if isLeap1 else ' '}") - print(f"{year}: \"{'L' if isLeap else ' '}\",") + print(f'{year}: "{"L" if isLeap else " "}",') # year -> f"{'L' if isLeap33 else ' '}{'L' if isLeap2820 else ' '}" isLeapDict = {