Skip to content

Commit 9fae4ab

Browse files
🚧 Move to ruff and PySide6.
1 parent e1e31b0 commit 9fae4ab

File tree

14 files changed

+219
-209
lines changed

14 files changed

+219
-209
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,4 +108,4 @@ ENV/
108108
*.crt
109109
plover_websocket_server_config.json
110110

111-
.pytest_cache/
111+
.pytest_cache/

.pre-commit-config.yaml

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,36 @@
1-
# .pre-commit-config.yaml
2-
31
repos:
42
- repo: https://github.com/asottile/pyupgrade
5-
rev: v3.15.2
3+
rev: v3.20.0
64
hooks:
7-
- id: pyupgrade
5+
- id: pyupgrade
6+
87
- repo: https://github.com/MarcoGorelli/absolufy-imports
9-
rev: v0.3.0
10-
hooks:
11-
- id: absolufy-imports
12-
- repo: https://github.com/ambv/black
13-
rev: 24.3.0
8+
rev: v0.3.1
149
hooks:
15-
- id: black
16-
language_version: python3.11
17-
- repo: https://github.com/pycqa/flake8
18-
rev: 7.0.0 # pick a git hash / tag to point to
19-
hooks:
20-
- id: flake8
10+
- id: absolufy-imports
11+
2112
- repo: https://github.com/pre-commit/pre-commit-hooks
22-
rev: v4.6.0
13+
rev: v5.0.0
2314
hooks:
2415
- id: trailing-whitespace
16+
exclude: ^src/pattern_identifier\.egg-info/
2517
- id: end-of-file-fixer
18+
exclude: ^src/pattern_identifier\.egg-info/
2619
- id: check-yaml
27-
- repo: https://github.com/pycqa/isort
28-
rev: 5.13.2
29-
hooks:
30-
- id: isort
31-
args: ["--profile", "black"]
32-
name: isort (python)
20+
3321
- repo: https://github.com/PyCQA/bandit
34-
rev: '1.7.8'
22+
rev: "1.8.3"
23+
hooks:
24+
- id: bandit
25+
args: ["--exclude", ".tox,.eggs,tests"]
26+
27+
- repo: https://github.com/astral-sh/ruff-pre-commit
28+
rev: "v0.11.13" # Use the latest version
3529
hooks:
36-
- id: bandit
37-
args: ["--exclude", ".tox,.eggs,tests"]
30+
- id: ruff
31+
args: ["--fix", "--exit-non-zero-on-fix"]
32+
- id: ruff-format
33+
# args: ["--check"] # Use --check in CI if you only want to verify
3834
- repo: local
3935
hooks:
4036
- id: pytest-check

plover_websocket_server/config.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
from copy import deepcopy
44
from json import dump, load
5-
from re import compile
5+
from pathlib import Path
6+
from re import compile as re_compile
67

78
from nacl.encoding import HexEncoder
89
from nacl.public import PrivateKey
@@ -19,6 +20,7 @@ class ServerConfig:
1920
Attributes:
2021
host: The host address for the server to run on.
2122
port: The port for the server to run on.
23+
2224
"""
2325

2426
host: str
@@ -32,10 +34,11 @@ def __init__(self, file_path: str) -> None:
3234
3335
Raises:
3436
IOError: Errored when loading the server configuration file.
35-
"""
3637
38+
"""
39+
file_path_obj = Path(file_path)
3740
try:
38-
with open(file_path, encoding="utf-8") as config_file:
41+
with file_path_obj.open(encoding="utf-8") as config_file:
3942
data: dict = load(config_file)
4043
except FileNotFoundError:
4144
data = {}
@@ -78,16 +81,13 @@ def __init__(self, file_path: str) -> None:
7881
# Save the updated data to the config file
7982
if loaded_data != data:
8083
log.info("Saving the updated data to the config file...")
81-
with open(file_path, "w", encoding="utf-8") as config_file:
84+
with file_path_obj.open("w", encoding="utf-8") as config_file:
8285
dump(data, config_file, indent=2)
8386

8487
# Assign values to class attributes
8588
self.host = data["host"]
8689
self.port = data["port"]
87-
self.remotes = [
88-
compile(remote["pattern"]) if "pattern" in remote else remote
89-
for remote in data["remotes"]
90-
]
91-
self.ssl = data.get("ssl", None)
90+
self.remotes = [re_compile(remote["pattern"]) if "pattern" in remote else remote for remote in data["remotes"]]
91+
self.ssl = data.get("ssl")
9292
self.private_key = private_key
9393
self.public_key = public_key

plover_websocket_server/listens.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from asyncio import Task, create_task, gather
1+
from asyncio import create_task, gather
22
from asyncio.futures import Future
33

44
from plover import log
@@ -22,11 +22,13 @@ def stop_listening(self) -> None:
2222

2323
class RawListens:
2424
def __get__(self, obj: Listens, objtype=None):
25+
"""Descriptor getter for accessing the status value."""
2526
value = obj._status
2627
# log.debug(f'Accessing status giving {value}')
2728
return value
2829

2930
def __set__(self, obj: Listens, value):
31+
"""Descriptor setter for updating the status value and notifying listeners."""
3032
# log.debug(f'Updating status to {value}')
3133
obj._status = value
3234
if len(obj._listeners):

plover_websocket_server/manager.py

Lines changed: 20 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
"""The middleman between Plover and the server."""
22

3-
import os
43
from datetime import datetime
54
from json import loads
65
from operator import itemgetter
7-
from typing import List
6+
from pathlib import Path
87

98
from aiohttp.web import WebSocketResponse
109
from jsonpickle import encode
@@ -23,28 +22,25 @@
2322
ERROR_NO_SERVER,
2423
ERROR_SERVER_RUNNING,
2524
)
26-
from plover_websocket_server.server import EngineServer, ServerStatus
27-
from plover_websocket_server.websocket.server import WebSocketServer
25+
from plover_websocket_server.websocket.server import ServerStatus, WebSocketServer
2826

2927
SERVER_CONFIG_FILE = "plover_websocket_server_config.json"
3028

3129

3230
class EngineServerManager:
3331
"""Manages a server that exposes the Plover engine."""
3432

35-
_server: EngineServer
33+
_server: WebSocketServer
3634
_tape_model: TapeModel
3735

3836
def __init__(self, engine: StenoEngine, test_mode: bool = False) -> None:
3937
self._server = None
4038
self._engine: StenoEngine = engine
41-
self._config_path: str = os.path.join(CONFIG_DIR, SERVER_CONFIG_FILE)
39+
self._config_path = Path(CONFIG_DIR).joinpath(SERVER_CONFIG_FILE)
4240
if self.get_server_status() != ServerStatus.Stopped:
4341
raise AssertionError(ERROR_SERVER_RUNNING)
4442

45-
self._config = ServerConfig(
46-
self._config_path
47-
) # reload the configuration when the server is restarted
43+
self._config = ServerConfig(self._config_path) # reload the configuration when the server is restarted
4844

4945
self._server = WebSocketServer(
5046
self._config.host,
@@ -66,6 +62,7 @@ def start(self) -> None:
6662
Raises:
6763
AssertionError: The server failed to start.
6864
IOError: The server failed to start.
65+
6966
"""
7067
self._server.start()
7168

@@ -78,8 +75,8 @@ def raw_stop(self) -> None:
7875
7976
Raises:
8077
AssertionError: The server failed to stop.
81-
"""
8278
79+
"""
8380
if self.get_server_status() != ServerStatus.Running:
8481
raise AssertionError(ERROR_NO_SERVER)
8582

@@ -97,8 +94,8 @@ def stop(self) -> None:
9794
9895
Raises:
9996
AssertionError: The server failed to stop.
100-
"""
10197
98+
"""
10299
self.raw_stop()
103100
log.info("Joining server thread...")
104101
self._server.join()
@@ -116,8 +113,8 @@ def get_server_status(self) -> ServerStatus:
116113
117114
Returns:
118115
The status of the server.
119-
"""
120116
117+
"""
121118
return self._server.listened.status if self._server else ServerStatus.Stopped
122119

123120
def join(self) -> None:
@@ -157,9 +154,7 @@ async def _on_message(self, data: dict) -> None:
157154
from plover.steno import Stroke
158155
from plover.translation import Translation, _mapping_to_macro
159156

160-
stroke = Stroke(
161-
[]
162-
) # required, because otherwise Plover will try to merge the outlines together
157+
stroke = Stroke([]) # required, because otherwise Plover will try to merge the outlines together
163158
# and the outline [] (instead of [Stroke([])]) can be merged to anything
164159
macro = _mapping_to_macro(mapping, stroke)
165160
if macro is not None:
@@ -181,7 +176,6 @@ async def _on_message(self, data: dict) -> None:
181176

182177
def _connect_hooks(self):
183178
"""Creates hooks into all of Plover's events."""
184-
185179
if not self._engine:
186180
raise AssertionError(ERROR_MISSING_ENGINE)
187181

@@ -194,7 +188,6 @@ def _connect_hooks(self):
194188

195189
def _disconnect_hooks(self):
196190
"""Removes hooks from all of Plover's events."""
197-
198191
self._server.data.stop_listening()
199192
if not self._engine:
200193
raise AssertionError(ERROR_MISSING_ENGINE)
@@ -211,6 +204,7 @@ def _on_stroked(self, stroke: Stroke):
211204
212205
Args:
213206
stroke: The stroke that was just performed.
207+
214208
"""
215209
stroke_json = encode(stroke, unpicklable=False)
216210
paper = self._tape_model._paper_format(stroke)
@@ -223,14 +217,14 @@ def _on_stroked(self, stroke: Stroke):
223217
}
224218
self._server.queue_message(data)
225219

226-
def _on_translated(self, old: List[_Action], new: List[_Action]):
220+
def _on_translated(self, old: list[_Action], new: list[_Action]):
227221
"""Broadcasts when a new translation occurs.
228222
229223
Args:
230224
old: A list of the previous actions for the current translation.
231225
new: A list of the new actions for the current translation.
232-
"""
233226
227+
"""
234228
old_json = encode(old, unpicklable=False)
235229
new_json = encode(new, unpicklable=False)
236230

@@ -244,8 +238,8 @@ def _on_machine_state_changed(self, machine_type: str, machine_state: str):
244238
machine_type: The name of the active machine.
245239
machine_state: The new machine state. This should be one of the
246240
state constants listed in plover.machine.base.
247-
"""
248241
242+
"""
249243
data = {
250244
"machine_state_changed": {
251245
"machine_type": machine_type,
@@ -259,8 +253,8 @@ def _on_output_changed(self, enabled: bool):
259253
260254
Args:
261255
enabled: If the output is now enabled or not.
262-
"""
263256
257+
"""
264258
data = {"output_changed": enabled}
265259
self._server.queue_message(data)
266260

@@ -270,8 +264,8 @@ def _on_config_changed(self, config_update: Config):
270264
Args:
271265
config_update: An object containing the full configuration or a
272266
part of the configuration that was updated.
273-
"""
274267
268+
"""
275269
config_json = encode(config_update, unpicklable=False)
276270

277271
data = {"config_changed": loads(config_json)}
@@ -282,8 +276,8 @@ def _on_dictionaries_loaded(self, dictionaries: StenoDictionaryCollection):
282276
283277
Args:
284278
dictionaries: A collection of the dictionaries that loaded.
285-
"""
286279
280+
"""
287281
data = {"dictionaries_loaded": "0"}
288282
self._server.queue_message(data)
289283

@@ -292,8 +286,8 @@ def _on_send_string(self, text: str):
292286
293287
Args:
294288
text: The string that was output.
295-
"""
296289
290+
"""
297291
data = {"send_string": text}
298292
self._server.queue_message(data)
299293

@@ -302,8 +296,8 @@ def _on_send_backspaces(self, count: int):
302296
303297
Args:
304298
count: The number of backspaces that were output.
305-
"""
306299
300+
"""
307301
data = {"send_backspaces": count}
308302
self._server.queue_message(data)
309303

@@ -314,38 +308,33 @@ def _on_send_key_combination(self, combination: str):
314308
combination: A string representing a sequence of key combinations.
315309
Keys are represented by their names based on the OS-specific
316310
keyboard implementations in plover.oslayer.
317-
"""
318311
312+
"""
319313
data = {"send_key_combination": combination}
320314
self._server.queue_message(data)
321315

322316
def _on_add_translation(self):
323317
"""Broadcasts when the add translation tool is opened via a command."""
324-
325318
data = {"add_translation": True}
326319
self._server.queue_message(data)
327320

328321
def _on_focus(self):
329322
"""Broadcasts when the main window is focused via a command."""
330-
331323
data = {"focus": True}
332324
self._server.queue_message(data)
333325

334326
def _on_configure(self):
335327
"""Broadcasts when the configuration tool is opened via a command."""
336-
337328
data = {"configure": True}
338329
self._server.queue_message(data)
339330

340331
def _on_lookup(self):
341332
"""Broadcasts when the lookup tool is opened via a command."""
342-
343333
data = {"lookup": True}
344334
self._server.queue_message(data)
345335

346336
def _on_suggestions(self):
347337
"""Broadcasts when the suggestions tool is opened via a command."""
348-
349338
data = {"suggestions": True}
350339
self._server.queue_message(data)
351340

@@ -354,6 +343,5 @@ def _on_quit(self):
354343
355344
Can be either a full quit or a restart.
356345
"""
357-
358346
data = {"quit": True}
359347
self._server.queue_message(data)

0 commit comments

Comments
 (0)