Skip to content

Commit a632a6e

Browse files
committed
refactor: apply ruff rules
1 parent f223b65 commit a632a6e

29 files changed

+616
-456
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
__pycache__
33
.mypy_cache
44
*.pickle
5+
.ruff_cache
6+
.tox
57

68
# build artifacts
79
dist/

.style.yapf

Lines changed: 0 additions & 3 deletions
This file was deleted.

lsp_utils/__init__.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from __future__ import annotations
2+
23
from ._client_handler import ClientHandler
34
from ._client_handler import notification_handler
45
from ._client_handler import request_handler
@@ -19,22 +20,22 @@
1920
from .uv_venv_manager import UvVenvManager
2021

2122
__all__ = [
23+
'SETTINGS_FILENAME',
2224
'ApiWrapperInterface',
2325
'ClientHandler',
24-
'download_file',
25-
'extract_archive',
2626
'GenericClientHandler',
2727
'NodeRuntime',
28-
'notification_handler',
2928
'NpmClientHandler',
3029
'PipVenvManager',
31-
'request_handler',
32-
'rmtree_ex',
3330
'ServerNpmResource',
3431
'ServerPipResource',
3532
'ServerResourceInterface',
3633
'ServerStatus',
37-
'SETTINGS_FILENAME',
3834
'UvRunner',
39-
'UvVenvManager'
35+
'UvVenvManager',
36+
'download_file',
37+
'extract_archive',
38+
'notification_handler',
39+
'request_handler',
40+
'rmtree_ex',
4041
]

lsp_utils/_client_handler/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from __future__ import annotations
2+
23
from .abstract_plugin import ClientHandler
34
from .api_decorator import notification_handler
45
from .api_decorator import request_handler

lsp_utils/_client_handler/abstract_plugin.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
from __future__ import annotations
2+
23
from ..api_wrapper_interface import ApiNotificationHandler
34
from ..api_wrapper_interface import ApiRequestHandler
45
from ..api_wrapper_interface import ApiWrapperInterface
56
from ..server_resource_interface import ServerStatus
67
from .api_decorator import register_decorated_handlers
78
from .interface import ClientHandlerInterface
8-
from abc import ABCMeta
9+
from abc import ABC
910
from functools import partial
1011
from LSP.plugin import AbstractPlugin
1112
from LSP.plugin import ClientConfig
@@ -16,18 +17,23 @@
1617
from LSP.plugin import Session
1718
from LSP.plugin import unregister_plugin
1819
from LSP.plugin import WorkspaceFolder
19-
from LSP.plugin.core.rpc import method2attr
20+
from LSP.plugin.core.rpc import method2attr # pyright: ignore[reportPrivateLocalImportUsage]
2021
from os import path
21-
from typing import Any, Callable
22+
from typing import Any
23+
from typing import Callable
24+
from typing import TYPE_CHECKING
2225
from typing_extensions import override
23-
from weakref import WeakMethod, ref
24-
import sublime
26+
from weakref import ref
27+
from weakref import WeakMethod
28+
29+
if TYPE_CHECKING:
30+
import sublime
2531

2632
__all__ = ['ClientHandler']
2733

2834

2935
class ApiWrapper(ApiWrapperInterface):
30-
def __init__(self, plugin: 'ref[AbstractPlugin]'):
36+
def __init__(self, plugin: ref[AbstractPlugin]) -> None:
3137
self.__plugin = plugin
3238

3339
def __session(self) -> Session | None:
@@ -72,15 +78,13 @@ def send_request(self, method: str, params: Any, handler: Callable[[Any, bool],
7278
session = self.__session()
7379
if session:
7480
request: Request[Any, Any] = Request(method, params)
75-
session.send_request(request, lambda result: handler(result, False), lambda result: handler(result, True))
81+
session.send_request(request, lambda result: handler(result, False), lambda result: handler(result, True)) # noqa: FBT003
7682
else:
77-
handler(None, True)
83+
handler(None, True) # noqa: FBT003
7884

7985

80-
class ClientHandler(AbstractPlugin, ClientHandlerInterface, metaclass=ABCMeta):
81-
"""
82-
The base class for creating an LSP plugin.
83-
"""
86+
class ClientHandler(AbstractPlugin, ClientHandlerInterface, ABC):
87+
"""The base class for creating an LSP plugin."""
8488

8589
# --- AbstractPlugin handlers -------------------------------------------------------------------------------------
8690

@@ -121,9 +125,9 @@ def can_start(cls, window: sublime.Window, initiating_view: sublime.View,
121125
if cls.manages_server():
122126
server = cls.get_server()
123127
if not server or server.get_status() == ServerStatus.ERROR:
124-
return "{}: Error installing server dependencies.".format(cls.package_name)
128+
return f"{cls.package_name}: Error installing server dependencies."
125129
if server.get_status() != ServerStatus.READY:
126-
return "{}: Server installation in progress...".format(cls.package_name)
130+
return f"{cls.package_name}: Server installation in progress..."
127131
message = cls.is_allowed_to_start(window, initiating_view, workspace_folders, configuration)
128132
if message:
129133
return message
@@ -167,6 +171,6 @@ def cleanup(cls) -> None:
167171

168172
def __init__(self, *args: Any, **kwargs: Any) -> None:
169173
super().__init__(*args, **kwargs)
170-
api = ApiWrapper(ref(self)) # type: ignore
174+
api = ApiWrapper(ref(self))
171175
register_decorated_handlers(self, api)
172176
self.on_ready(api)

lsp_utils/_client_handler/api_decorator.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,21 @@
11
from __future__ import annotations
2-
from ..api_wrapper_interface import ApiWrapperInterface
3-
from .interface import ClientHandlerInterface
4-
from typing import Any, Callable, List, TypeVar, Union
2+
3+
from typing import Any
4+
from typing import Callable
5+
from typing import List
6+
from typing import TYPE_CHECKING
7+
from typing import TypeVar
8+
from typing import Union
59
import inspect
610

11+
if TYPE_CHECKING:
12+
from ..api_wrapper_interface import ApiWrapperInterface
13+
from .interface import ClientHandlerInterface
14+
715
__all__ = [
816
"notification_handler",
9-
"request_handler",
1017
"register_decorated_handlers",
18+
"request_handler",
1119
]
1220

1321
T = TypeVar('T')
@@ -24,31 +32,28 @@
2432

2533
def notification_handler(notification_methods: MessageMethods) -> Callable[[NotificationHandler], NotificationHandler]:
2634
"""
27-
Marks the decorated function as a "notification" message handler.
35+
Mark the decorated function as a "notification" message handler.
2836
2937
On server sending the notification, the decorated function will be called with the `params` argument which contains
3038
the payload.
3139
"""
32-
3340
return _create_handler("notification", notification_methods)
3441

3542

3643
def request_handler(request_methods: MessageMethods) -> Callable[[RequestHandler], RequestHandler]:
3744
"""
38-
Marks the decorated function as a "request" message handler.
45+
Mark the decorated function as a "request" message handler.
3946
4047
On server sending the request, the decorated function will be called with two arguments (`params` and `respond`).
4148
The first argument (`params`) is the payload of the request and the second argument (`respond`) is the function that
4249
must be used to respond to the request. The `respond` function takes any data that should be sent back to the
4350
server.
4451
"""
45-
4652
return _create_handler("request", request_methods)
4753

4854

4955
def _create_handler(client_event: str, message_methods: MessageMethods) -> Callable[[T], T]:
50-
""" Marks the decorated function as a message handler. """
51-
56+
"""Mark the decorated function as a message handler."""
5257
message_methods = [message_methods] if isinstance(message_methods, str) else message_methods
5358

5459
def decorator(func: T) -> T:

lsp_utils/_client_handler/interface.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
11
from __future__ import annotations
2-
from ..api_wrapper_interface import ApiWrapperInterface
3-
from ..server_resource_interface import ServerResourceInterface
4-
from abc import ABCMeta
2+
3+
from abc import ABC
54
from abc import abstractmethod
6-
from LSP.plugin import ClientConfig
7-
from LSP.plugin import DottedDict
8-
from LSP.plugin import WorkspaceFolder
9-
import sublime
5+
from typing import TYPE_CHECKING
6+
7+
if TYPE_CHECKING:
8+
from ..api_wrapper_interface import ApiWrapperInterface
9+
from ..server_resource_interface import ServerResourceInterface
10+
from LSP.plugin import ClientConfig
11+
from LSP.plugin import DottedDict
12+
from LSP.plugin import WorkspaceFolder
13+
import sublime
1014

1115
__all__ = ['ClientHandlerInterface']
1216

1317

14-
class ClientHandlerInterface(metaclass=ABCMeta):
18+
class ClientHandlerInterface(ABC):
1519
package_name: str = ''
1620

1721
@classmethod

lsp_utils/_util/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
from __future__ import annotations
2+
23
from .download_file import download_file
34
from .download_file import extract_archive
5+
from .logging import logger
46

57
__all__ = [
68
'download_file',
79
'extract_archive',
10+
'logger',
811
]

lsp_utils/_util/download_file.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
from __future__ import annotations
2-
from pathlib import Path
2+
33
from shutil import copyfileobj
4-
from urllib.request import HTTPError, urlopen
4+
from typing import TYPE_CHECKING
5+
from urllib.request import urlopen
56
from zipfile import ZipFile
67
import tarfile
78

9+
if TYPE_CHECKING:
10+
from pathlib import Path
811

912
__all__ = [
1013
'download_file',
@@ -14,12 +17,8 @@
1417

1518
def download_file(url: str, target_path: Path) -> None:
1619
"""Download given URL to the specified target file path."""
17-
try:
18-
with urlopen(url) as response, target_path.open('wb') as out_file:
19-
copyfileobj(response, out_file)
20-
except HTTPError as ex:
21-
print(f'Failed downloading URL: {url}')
22-
raise ex
20+
with urlopen(url) as response, target_path.open('wb') as out_file: # noqa: S310
21+
copyfileobj(response, out_file)
2322

2423

2524
def extract_archive(archive_file: Path, target_directory: Path) -> Path:
@@ -39,16 +38,18 @@ def extract_archive(archive_file: Path, target_directory: Path) -> Path:
3938
with tarfile.open(archive_file, 'r:*') as archive:
4039
return extract_files_from_archive(archive, target_directory)
4140
else:
42-
raise Exception(f'Unsupported archive "{archive_name}"')
41+
msg = f'Unsupported archive "{archive_name}"'
42+
raise Exception(msg)
4343

4444

4545
def extract_files_from_archive(archive: ZipFile | tarfile.TarFile, target_directory: Path) -> Path:
4646
names = archive.namelist() if isinstance(archive, ZipFile) else archive.getnames()
47-
bad_members = [x for x in names if x.startswith('/') or x.startswith('..')]
47+
bad_members = [x for x in names if x.startswith(('/', '..'))]
4848
if bad_members:
49-
raise Exception(f'archive appears to be malicious, bad filenames: {bad_members}')
49+
msg = f'archive appears to be malicious, bad filenames: {bad_members}'
50+
raise Exception(msg)
5051
topdir_name = get_top_level_directory(names)
51-
archive.extractall(str(target_directory))
52+
archive.extractall(str(target_directory)) # noqa: S202
5253
if topdir_name:
5354
return target_directory / topdir_name
5455
return target_directory
@@ -57,9 +58,9 @@ def extract_files_from_archive(archive: ZipFile | tarfile.TarFile, target_direct
5758
def get_top_level_directory(names: list[str]) -> str | None:
5859
"""
5960
Check if all files in a list are contained within a parent directory.
61+
6062
Returns str | None: Common parent name if present.
6163
"""
62-
6364
# Filter out directory entries and get top-level paths.
6465
top_levels: set[str] = set()
6566
for name in names:

lsp_utils/_util/logging.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from __future__ import annotations
2+
3+
import logging
4+
5+
__all__ = [
6+
'logger',
7+
]
8+
9+
logger = logging.getLogger(str(__package__).split('.')[0])
10+
handler = logging.StreamHandler()
11+
handler.setFormatter(logging.Formatter('[%(name)s] %(levelname)s: %(message)s'))
12+
logger.addHandler(handler)
13+
logger.setLevel(logging.DEBUG)

0 commit comments

Comments
 (0)